SQL PHP按天计算两个日期之间的数据,并显示每天的记录

时间:2017-10-31 14:07:29

标签: php mysql sql

我的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语句是有效的,但结果不是我想要的

Here is the result

enter image description here

它应该显示五个记录,其中日等于25,26,27,28,29,30

但是当c1,c2,c3,c4和c5都等于0时,它没有显示该行而不是显示所有0

如何解决问题?

1 个答案:

答案 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 - 这可以在性能方面更好。我发现上述方法可以更快地获得所需的结果。

其他一些说明:

  • MySQL将布尔表达式视为数字上下文中的数字,使用&#34; 1&#34;真的。您不需要CASE
  • 字符串分隔符的ANSI标准是单引号,而不是双引号。
  • 日期逻辑使用日期更简单。无需担心最后一笔交易何时在任何一天。
  • 如果您选择六天的数据,为什么要使用LIMIT 5