2012-04-11 83 views
4

我有以下表的消息:計數的消息在一個結果

+---------+---------+------------+----------+ 
| msg_id | user_id | _date  | _time | 
+-------------------+------------+----------+ 
| 1  | 1  | 2011-01-22 | 06:23:11 | 
| 2  | 1  | 2011-01-23 | 16:17:03 | 
| 3  | 1  | 2011-01-23 | 17:05:45 | 
| 4  | 2  | 2011-01-22 | 23:58:13 | 
| 5  | 2  | 2011-01-23 | 23:59:32 | 
| 6  | 3  | 2011-01-22 | 13:45:00 | 
| 7  | 3  | 2011-01-23 | 13:22:34 | 
| 8  | 3  | 2011-01-23 | 18:22:34 | 
+---------+---------+------------+----------+ 

我要的是每一天,看看有多少郵件的每個用戶之前發送和16:00後。我現在做的這兩個步驟:

SELECT user_id, _date, COUNT(msg_id) AS cnt 
FROM messages WHERE _time <= '16:00' 
GROUP BY user_id, _date ORDER BY user_id, _date ASC 

user_id _date  cnt 
----------------------------- 
1  2011-01-22 1 
1  2011-01-23 0 
2  2011-01-22 0 
2  2011-01-23 0 
3  2011-01-22 1 
3  2011-01-23 1 

SELECT user_id, _date, COUNT(msg_id) AS cnt 
FROM messages WHERE _time > '16:00' 
GROUP BY user_id, _date ORDER BY user_id, _date ASC 

user_id _date  cnt 
----------------------------- 
1  2011-01-22 0 
1  2011-01-23 2 
2  2011-01-22 1 
2  2011-01-23 1 
3  2011-01-22 0 
3  2011-01-23 1 

(在現實中,順便說一句,用「0」值的行不會在結果給予我只是說他們澄清)

我想將這兩個輸出合併爲一個:

user_id _date  before16 after16 
------------------------------------- 
1  2011-01-22 1   0 
1  2011-01-23 0   2 
2  2011-01-22 0   1 
2  2011-01-23 0   1 
3  2011-01-22 1   0 
3  2011-01-23 1   1 

但是,我不知道如何編寫此查詢。如果你這樣做,你的幫助會:-)

回答

4

理解試試這個:

SELECT 
    user_id, 
    _date, 
    SUM(_time <= '16:00') AS before16, 
    SUM(_time > '16:00') AS after16 
FROM messages 
GROUP BY user_id, _date 
ORDER BY user_id, _date ASC 
+1

感謝的人,這讓我很快樂。 (已經自己添加了GROUP BY :-) – Pr0no 2012-04-11 19:07:55