2013-11-03 91 views
2

你好,我用這個SQL查詢來獲取基於每月的圖表表示在過去12次月的記錄:Mysql的總和除以一個月的過去12個月

SELECT DATE_FORMAT(drives.timestamp, "%b") AS Month, 
         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) ORDER BY drives.timestamp Asc 
然而

如果沒有記錄一個月沒有按預期包含在結果集中,而且我正在用php做很多計算來實現我想要的結果。

我的問題是這樣的:有沒有辦法在過去12個月中檢索每月驅動器總和的簡單結果集,並且如果一個月內有0個驅動器,則它必須也包括在內 - 顯示在結果集。

回答

3

您需要使用包含每個月的行的表進行外連接。假設你沒有這樣的表,你可以在飛行中使用硬編碼的UNION查詢創建:

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 

沒有記錄任何個月內將有一個排,在數據列NULL