我有这张桌子
user_id DATE start_time end_time
1234 11/16/2013 8.30 9.30
1234 11/16/2013 9.30 10.30
1234 11/16/2013 12.30 13.30
1234 11/19/2013 8.30 9.30
我想按如下方式汇总数据,将时间段分组:
user_id DATE start_time end_time
1234 11/16/2013 8.30 10.30
1234 11/16/2013 12.30 13.30
1234 11/19/2013 8.30 9.30
我如何在MySQL中执行此操作?
答案 0 :(得分:0)
可能的解决方案
SELECT user_id, date, MIN(start_time) start_time, MAX(end_time) end_time
FROM
(
SELECT user_id, date, start_time, end_time,
@n := IF(@u = user_id AND @d = date AND CAST(@e AS TIME) = start_time, @n, @n + 1) rnum,
@u := user_id, @d := date, @e := end_time
FROM table1 CROSS JOIN (SELECT @n := 0, @u := NULL, @d := NULL, @e := NULL) i
ORDER BY user_id, date, start_time, end_time
) q
GROUP BY user_id, date, rnum
输出:
+---------+------------+------------+----------+ | user_id | date | start_time | end_time | +---------+------------+------------+----------+ | 1234 | 2013-11-16 | 08:30:00 | 10:30:00 | | 1234 | 2013-11-16 | 12:30:00 | 13:30:00 | | 1234 | 2013-11-19 | 08:30:00 | 09:30:00 | +---------+------------+------------+----------+
这是 SQLFiddle 演示