我的应用程序中有用户的活动表,我需要显示聚合 报告2分钟。范围。
id datetime userid activity
-- ------------------- ------ --------
1 2014-27-12 02:10:57 1 'read'
2 2014-27-12 02:10:59 1 'ok'
3 2014-27-12 02:11:02 1 'write'
4 2014-27-12 02:13:03 1 'write'
5 2014-27-12 02:15:06 1 'write'
6 2014-27-12 02:15:08 1 'ok'
7 2014-27-12 02:17:07 1 'read'
8 2014-27-12 02:18:01 1 'read'
9 2014-27-12 02:18:02 1 'read'
10 2014-27-12 02:18:05 1 'read'
11 2014-27-12 02:18:25 1 'read'
12 2014-27-12 02:21:09 1 'read'
我想在2个小时范围内得到如下结果。
userid id datetime (min) datetime (max) count
------ -- ------------------- ------------------- -----
1 1 2014-27-12 02:10:57 2014-27-12 02:11:02 3
1 4 2014-27-12 02:13:03 2014-27-12 02:15:08 3
1 7 2014-27-12 02:17:07 2014-27-12 02:18:25 5
1 12 2014-27-12 02:21:09 2014-27-12 02:21:09 1
有谁能解释,怎么做?
答案 0 :(得分:1)
SELECT userid, min(id) AS id,
MIN(datetime) AS `datetime (min)`, MAX(datetime) AS `datetime (max)`,
COUNT(*) AS count
FROM activity
GROUP BY userid, FLOOR(UNIX_TIMESTAMP(datetime)/120)