MySQL填补日期空白

时间:2019-05-14 23:21:36

标签: mysql sql left-join

我正在尝试从过去7天的dataTable中获取值,如果在特定日期没有数据应在输出中填充零:

SELECT calendar.dt, COALESCE(SUM(weight*price),0) AS amount
FROM
    (SELECT CURRENT_DATE AS dt
       UNION ALL SELECT CURRENT_DATE - INTERVAL 1 DAY
       UNION ALL SELECT CURRENT_DATE - INTERVAL 2 DAY
       UNION ALL SELECT CURRENT_DATE - INTERVAL 3 DAY
       UNION ALL SELECT CURRENT_DATE - INTERVAL 4 DAY
       UNION ALL SELECT CURRENT_DATE - INTERVAL 5 DAY
       UNION ALL SELECT CURRENT_DATE - INTERVAL 6 DAY) calendar
LEFT JOIN dataTable ON calendar.dt = DATE(dataTable.sold_at);

以上请求仅返回一条记录:

enter image description here

请告知SQL请求出了什么问题?

1 个答案:

答案 0 :(得分:0)

似乎缺少group by

SELECT calendar.dt, COALESCE(SUM(weight*price),0) AS amount
FROM
    (SELECT CURRENT_DATE AS dt
       UNION ALL SELECT CURRENT_DATE - INTERVAL 1 DAY
       UNION ALL SELECT CURRENT_DATE - INTERVAL 2 DAY
       UNION ALL SELECT CURRENT_DATE - INTERVAL 3 DAY
       UNION ALL SELECT CURRENT_DATE - INTERVAL 4 DAY
       UNION ALL SELECT CURRENT_DATE - INTERVAL 5 DAY
       UNION ALL SELECT CURRENT_DATE - INTERVAL 6 DAY) calendar
LEFT JOIN dataTable ON calendar.dt = DATE(dataTable.sold_at)
Group by calendar.dt
;

SQL小提琴链接:http://sqlfiddle.com/#!9/f151a8e/4