我正在尝试从过去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);
以上请求仅返回一条记录:
请告知SQL请求出了什么问题?
答案 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