2013-11-09 108 views
0

猜猜這個問題有很多varianat,但是這有一個轉折。MySQL左加入SUM不包括0

我的主表中包含記錄的公里爲特定日期爲特定用戶:

km_run

|entry|mnumber|dato |km |其中「拿督」是具體的日期。格式如下:

|1 |3 |2013-01-01|5.7 |

對於特定用戶('mnumber'),我想計算一年中每週的總和。爲此我做了一個「啞表」只是包含週數從1到53:

Table `week_list`: 
|week| 
|1 | 
|2 | 

等。

該查詢給出的總和,但是我無法找到一個方法來返回如果「km_run」中沒有特定周的條目,則爲零。

SELECT `week_list`.`week`, WEEKOFYEAR(`km_run`.`dato`), SUM(`km_run`.`km`) 
FROM `week_list` LEFT JOIN `km_run` ON WEEKOFYEAR(`dato`) = `week_list`.`week` 
WHERE `km_run`.`mnumber` = 3 AND `km_run`.`dato` >= '2013-01-01' 
AND `km_run`.`dato` < '2014-01-01' 
GROUP BY WEEKOFYEAR(`dato`) 

我試圖做COALESCE(SUM(km),0),我也曾嘗試使用周圍的總和IFNULL函數。儘管有左連接,但並不是所有來自week_list的記錄都在sql語句中返回。

這裏的結果:

week | WEEKOFYEAR(`km_run`.`dato`) | SUM(`km_run`.`km`) 
1 | 1       | 58.4 
3 | 3       | 50.7 
4 | 4       | 39.2 

正如你可以看到兩個星期跳過,而不是返回一個0

+2

請新增小提琴您的樣本數據集,這將是有益的 –

回答

1

首先JOIN的工作,創造這樣的行:
week=2 weekofyear=null mnumber=null sum=0 ...
然後,WHERE條款(例如,where mnumber=3)排除了具有空值的行。 你可以嘗試這樣的事:

SELECT week, SUM(km) FROM (
    (SELECT km_run.km AS km, WEEKOFYEAR(km_run.dato) AS week 
    FROM km_run 
    WHERE mnumber = 3 AND km_run.dato >= '2013-01-01' AND km_run.dato < '2014-01-01') 
    UNION 
    (SELECT 0 AS km, week_list.week as week FROM week_list) 
) GROUP BY week 
+0

輝煌的解決方案。只需要一個小的修正,以我的MySQL服務器上的工作:FROM( 'SELECT周,SUM(公里)(SELECT km_run.km AS公里,WEEKOFYEAR(km_run.dato)AS 一週km_run WHERE mnumber = 3 AND km_run.dato> ='2013-01-01'AND km_run.dato <'2014-01-01') UNION (SELECT 0 AS km,week_list.week as week FROM FROM_list) )AS derivedtable GROUP按周計算# 謝謝! :-) – kWalk