我有这样的查询:
SELECT SUM(spend.price) AS total, WEEKDAY(spend.date) AS weekday
FROM spend
WHERE spend.date BETWEEN '2012-11-01' AND '2012-11-07'
GROUP BY WEEKDAY(spend.date) ;
现在,查询只向我提供了用户付款的日期。
total weekday
60 2
10 3
3 5
3 6
但我想在没有付款的情况下每天给我0(零)。
total weekday
0 1
60 2
10 3
0 4
3 5
3 6
0 7
表架构here。
答案 0 :(得分:1)
这是原始语法:
SELECT SUM(spend.price) AS total, day AS weekday
FROM (SELECT price, WEEKDAY(date) as day FROM spend WHERE date BETWEEN '2012-11-01' AND '2012-11-07'
UNION ALL
SELECT 0,0
UNION ALL
SELECT 0,1
UNION ALL
SELECT 0,2
UNION ALL
SELECT 0,3
UNION ALL
SELECT 0,4
UNION ALL
SELECT 0,5
UNION ALL
SELECT 0,6
) spend
GROUP BY day ;
这是缩短的:
CREATE TEMPORARY TABLE tmp ( `price` int, `day` int );
INSERT INTO tmp VALUES (0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(0,6);
SELECT SUM(spend.price) AS total, day AS weekday
FROM (SELECT price, WEEKDAY(date) as day FROM spend WHERE date BETWEEN '2012-11-01' AND '2012-11-07'
UNION ALL
SELECT * FROM tmp
) spend
GROUP BY day ;