我的sql代码有问题, 这是代码:
SELECT
COUNT(CASE WHEN ItemState = 1 THEN 1 ELSE NULL END) AS C1,
COUNT(CASE WHEN ItemState = 3 THEN 1 ELSE NULL END) AS C2,
COUNT(CASE WHEN ItemState = 5 THEN 1 ELSE NULL END) AS C3,
COUNT(CASE WHEN ItemState = 7 THEN 1 ELSE NULL END) AS C4,
COUNT(CASE WHEN ItemState = 10 THEN 1 ELSE NULL END) AS C5,
DAY(LastUpdate) AS Day
FROM purchasehistory
WHERE ItemID=77
AND LastUpdate BETWEEN "2017-10-25 00:00:00" AND "2017-10-30 23:59:59"
GROUP BY Day
ORDER BY LastUpdate
LIMIT 5
count语句是有效的,但结果不是我想要的
它应该显示五个记录,其中日等于25,26,27,28,29,30
但是当c1,c2,c3,c4和c5都等于0时,它没有显示该行而不是显示所有0
如何解决问题?
答案 0 :(得分:2)
我发现在许多情况下解决此问题的一种简单方法是将一些过滤条件移到case
条件中:
SELECT SUM(ItemID = 77 AND ItemState = 1) AS C1,
SUM(ItemID = 77 AND ItemState = 3) AS C2,
SUM(ItemID = 77 AND ItemState = 5) AS C3,
SUM(ItemID = 77 AND ItemState = 7) AS C4,
SUM(ItemID = 77 AND ItemState = 10) AS C5,
DAY(LastUpdate) AS Day
FROM purchasehistory
WHERE LastUpdate >= '2017-10-25' AND LastUpdate < '2017-10-31'
GROUP BY Day
ORDER BY MIN(LastUpdate)
LIMIT 5;
这假设每天至少有一种产品。
更典型的解决方案是使用LEFT JOIN
- 这可以在性能方面更好。我发现上述方法可以更快地获得所需的结果。
其他一些说明:
CASE
。LIMIT 5
?