按时间分组,其中时间是在mysql中的日期列?

时间:2013-05-28 08:57:22

标签: mysql

ID         Date
1          2013-01-11 00:57:25 
2          2013-02-01 02:17:05 
3          2013-02-05 03:12:23
4          2013-02-17 10:17:02
5          2013-02-19 11:27:25
6          2013-02-27 13:42:13
7          2013-03-09 15:57:25
8          2013-03-12 16:00:00
9          2013-04-10 19:39:18
10         2013-05-16 20:46:38

我想根据此表中的时间Group ID。请记住,日期位于一列中,因此我可以根据不同的时间从日期列和组中获取时间。

就像我想要ID来自00:00:00 to 12:00:00的{​​{1}}来自12:00:00 to 24:00:00中另一个群组的mysql

2 个答案:

答案 0 :(得分:3)

SELECT
CASE WHEN TIME(`Date`) BETWEEN '00:00:00' AND '12:00:00' THEN 'early' ELSE 'late' END AS myTime,
COUNT(*)
FROM yourTable
GROUP BY myTime

您还可以轻松添加多个“群组”:

SELECT
CASE WHEN TIME(`Date`) BETWEEN '00:00:00' AND '03:00:00' THEN '0-3' 
CASE WHEN TIME(`Date`) BETWEEN '03:00:01' AND '06:00:00' THEN '3-6'
ELSE 'later' END AS myTime,
COUNT(*)
FROM yourTable
GROUP BY myTime

答案 1 :(得分:1)

提示:

SELECT HOUR(Date), COUNT(*)
FROM your_table
GROUP BY HOUR(Date);