Mysql
 sql >> Database >  >> RDS >> Mysql

Mysql somma dei record per mese negli ultimi 12 mesi

Devi eseguire un outer join con una tabella che contiene una riga per ogni mese. Supponendo che tu non abbia una tabella del genere, puoi crearla al volo con una query UNION hardcoded:

SELECT * FROM
    (SELECT DATE_FORMAT(now(), "%b") as Month
     UNION
     SELECT DATE_FORMAT(now() - INTERVAL 1 MONTH), "%b")
     UNION
     SELECT DATE_FORMAT(now() - INTERVAL 2 MONTH), "%b")
     UNION
     ...
     SELECT DATE_FORMAT(now() - INTERVAL 11 MONTH), "%b")) AS Months
LEFT JOIN (SELECT DATE_FORMAT(drives.timestamp, "%b") AS Month,
                 drives.timestamp,
                 DATE_FORMAT(drives.timestamp, "%d-%m-%Y %H:%i:%s") AS Exact_date,
                 drives.departure,
                 drives.destination,
                 drives.route,
                 CONCAT(drivers.name, " ", drivers.surname) as driver,
                 drivers.id as driver_id
                 FROM drives, drivers WHERE drives.driver = drivers.id 
                 AND drives.timestamp > DATE_SUB(now(), INTERVAL 12 MONTH)) data
ON Months.Month = data.Month
ORDER BY data.timestamp

Tutti i mesi senza record avranno una riga con NULL nelle colonne dei dati.