按小时分组显示日期范围MYSQL中每天的细分

时间:2014-11-24 20:32:32

标签: mysql date

我正在尝试创建一个查询,以显示按小时分组的与财务合同相关的潜在客户细分。

这是我到目前为止几个小时的例子:

SELECT CONCAT(HOUR(received), ':00-', HOUR(received)+1, ':00') AS Hours, 
COUNT(*) as `leads`
FROM (digital_lead)
WHERE `received` BETWEEN '2014-11-01 00:00:00' AND '2014-11-24 00:00:00'
GROUP BY HOUR(received)

这是结果......

 Hours   usage

0:00-1:00   36
1:00-2:00   25
2:00-3:00   16
3:00-4:00   4
4:00-5:00   7
5:00-6:00   8
6:00-7:00   13 // etc all the way to 23:00 - 24:00

好的 - 这似乎有效,但是,它会在leads语句中设置的时段内聚合该时段的所有BETWEEN。我希望能够显示期间范围内每天每小时的细分。

这看起来像是:

Date        Hours         leads
2014-11-01      
            0:00-1:00      36
            1:00-2:00      25
            2:00-3:00      16
            3:00-4:00      4
            4:00-5:00      7
            5:00-6:00      8
            6:00-7:00      13 // etc all the way to 23:00 - 24:00

因此将显示每个日期,然后显示当天的小时数等等。

感谢。

1 个答案:

答案 0 :(得分:2)

按日期分组:

SELECT DATE(received), HOUR(received), ...
...
GROUP BY DATE(received), HOUR(received)

由于您只按小时()进行分组,因此您必须获得

Hour
1      sum of leads in hour 1 of jan 1, jan 2, jan 3, ... dec 31
2      sum of leads in hour 2 of jan 1, jan 2, jan 3, ... dec 31

而不是

Jan 1  Hour 1  sum of leads for just that one hour on the one day
Jan 1  Hour 2  sum of leads for just that one hour on the one day
..
Dec 31  Hour 23 sum of leads