得到不存在日期的结果

时间:2016-08-07 15:08:18

标签: mysql sql

我有一个包含具有DATETIME时间戳的事件的MySql表。我想计算每一天的活动。在某些日子里,例如星期天,活动不见了。结果应包含这些天,计数为零。

我的查询如下:

SELECT 

COUNT(1) AS mycount,
DATE_FORMAT(DATE(evaluations.timestamp),"%a, %d.%m.%Y") AS date
FROM Events 
GROUP BY DATE(timestamp)
ORDER BY DATE(timestamp) DESC

我可以在不使用包含所有日期的帮助程序表的情况下修改查询吗? 单个查询(没有进展,没有功能)没问题。

1 个答案:

答案 0 :(得分:1)

如果您没有任何calendar表:

,查询会以某种方式显示
SELECT 
 dateTable.day,
 COALESCE(t.mycount,0) AS cnt
FROM 
(
SELECT ADDDATE((SELECT MIN(DATE(timestamp)) FROM Events), INTERVAL @i:=@i+1 DAY) AS DAY
FROM (
SELECT a.a
FROM (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS a
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS b
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS c
) a
JOIN (SELECT @i := -1) r1
WHERE 
@i < DATEDIFF((SELECT MAX(DATE(timestamp)) FROM Events), (SELECT MIN(DATE(timestamp)) FROM Events))
) AS dateTable
LEFT JOIN 
(
        SELECT 
        COUNT(1) AS mycount,
        DATE_FORMAT(DATE(evaluations.timestamp),"%a, %d.%m.%Y") AS date
        FROM Events 
        GROUP BY DATE(timestamp)
        ORDER BY DATE(timestamp) DESC
) AS t
ON dateTable.day = t.date
ORDER BY dateTable.day DESC;

注意:

如果您认为您经常需要这种查询,那么您可以创建一个表格,其中包含所有日期。 可以通过mysql event定期添加更新的日期

然后工作很简单。只需要在LEFT JOIN表和查询结果之间设置calendar即可。