0

我有一个这样的查询:

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

表架构在这里

4

1 回答 1

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 ;

这是一个演示:http ://sqlfiddle.com/#!2/8c323/3/0

于 2012-11-26T15:39:45.000 回答