在mysql中按小时计算最近12小时内的所有记录

时间:2016-01-07 08:10:25

标签: mysql

我想在最近12小时内从我的mysql表中计算每小时的记录数。

我找到了这个link,但我的问题是,现在说它是2016年1月7日,上午9点,然后我想计算从1月7日上午9点到1月6日晚上9点的记录。 我的表结构如下:

Table name :: cebod_cdr

id|userid|starting_date|total_duration
1 | 17 | 2016-01-07 09:00:00 | 12
2 | 17 | 2016-01-07 07:30:24 | 45
3 | 17 | 2016-01-07 01:12:21 | 5
4 | 17 | 2016-01-06 10:30:00 | 18
5 | 17 | 2016-01-06 10:45:00 | 25

示例输出

hour | calls
9AM | 1
8AM | 0
7AM | 1
6AM | 0
5AM | 0
4AM | 0
3AM | 0
2AM | 0
1AM | 1
12AM | 0
11PM | 0
10PM | 2

如果以所需格式(1-12)显示小时数有任何问题,我可以用24小时格式等其他格式显示。

3 个答案:

答案 0 :(得分:1)

SELECT HOUR(starting_date) AS Hour, COUNT(*) AS calls
FROM cebod_cdr
WHERE starting_date > DATE_ADD(NOW(), INTERVAL -12 HOUR)
GROUP BY HOUR(starting_date)

答案 1 :(得分:1)

试试这个:

SELECT
    date_format(dh.starting_date, '%Y-%m-%d %H:%i:%s') as hour,
    COUNT(md.id) AS count
FROM
    cebod_cdr dh 
    LEFT JOIN cebod_cdr md ON dh.starting_date = DATE_FORMAT(md.starting_date, '%Y-%m-%d %H:00:00')
WHERE dh.starting_date >= DATE_SUB(NOW(),INTERVAL 12 HOUR)
    AND dh.starting_date <  NOW()
GROUP BY dh.starting_date
ORDER BY dh.starting_date

答案 2 :(得分:0)

我找到了如下答案:

    SELECT za_hours.za_hour as hour, COUNT(id) as calls 
    FROM ( 
    SELECT NOW() - INTERVAL 1 HOUR as za_hour UNION 
    SELECT NOW() - INTERVAL 2 HOUR as za_hour UNION 
    SELECT NOW() - INTERVAL 3 HOUR as za_hour UNION 
    SELECT NOW() - INTERVAL 4 HOUR as za_hour UNION 
    SELECT NOW() - INTERVAL 5 HOUR as za_hour UNION 
    SELECT NOW() - INTERVAL 6 HOUR as za_hour UNION 
    SELECT NOW() - INTERVAL 7 HOUR as za_hour UNION 
    SELECT NOW() - INTERVAL 8 HOUR as za_hour UNION 
    SELECT NOW() - INTERVAL 9 HOUR as za_hour UNION 
    SELECT NOW() - INTERVAL 10 HOUR as za_hour UNION 
    SELECT NOW() - INTERVAL 11 HOUR as za_hour UNION 
    SELECT NOW() - INTERVAL 12 HOUR as za_hour ) 
    za_hours 
    LEFT JOIN 
    cebod_cdr 
    ON DATE_FORMAT(za_hours.za_hour, '%Y-%m-%d %H:') = DATE_FORMAT(starting_date, '%Y-%m-%d %H:') 
    AND starting_date >= NOW() - INTERVAL 12 HOUR
    GROUP BY za_hours.za_hour 
    ORDER BY za_hours.za_hour

请建议我是否可以改进此查询。