2013-11-22 67 views
0

我有這個表使用GROUP BY或任何其他方法彙總MySQL數據

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中執行此操作?

+1

所以它記錄刪除這個'summary'? –

+0

我認爲OP的原始格式表明user_id「1234」和「1234」是不同的。那是對的嗎? – bitfiddler

+0

user_id「1234」和「1234」沒有什麼不同 –

回答

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演示