MySQL LEFT JOIN SUM不包含0

时间:2013-11-09 14:29:10

标签: mysql sum left-join week-number

猜猜这个问题有很多变种,但这有一个转折。

我的主表包含特定用户的特定日期的已记录公里数:

km_run

|entry|mnumber|dato |km |其中'dato'是具体日期。格式如下:

|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

1 个答案:

答案 0 :(得分: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