mysql查询24小时各时段,没有的也返回时段 和零 根据日期分组取最大值
时间: 2024-03-12 09:47:24 浏览: 64
可以使用以下SQL语句来查询24小时各时段的数据,没有数据的时段也会返回时段和零,并且根据日期分组取最大值。
```
SELECT DATE(time_column) AS date, HOUR(time_column) AS hour, IFNULL(COUNT(*), 0) AS count
FROM (
SELECT DATE_SUB(NOW(), INTERVAL 24 HOUR) + INTERVAL hour HOUR AS time_column
FROM (
SELECT 0 AS hour UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12 UNION SELECT 13 UNION SELECT 14 UNION SELECT 15 UNION SELECT 16 UNION SELECT 17 UNION SELECT 18 UNION SELECT 19 UNION SELECT 20 UNION SELECT 21 UNION SELECT 22 UNION SELECT 23
) AS hours
) AS time_table
LEFT JOIN table_name ON time_table.time_column <= table_name.time_column AND table_name.time_column < time_table.time_column + INTERVAL 1 HOUR
WHERE time_table.time_column BETWEEN DATE_SUB(NOW(), INTERVAL 24 HOUR) AND NOW()
GROUP BY date, hour
ORDER BY date DESC, hour DESC
```
其中,time_column为时间列的列名,table_name为表名。这条SQL语句会统计最近24小时内每个小时的数据量,如果某个小时没有数据,也会返回该小时的时段和数据量0,并且根据日期分组取最大值。
阅读全文