我有下表的消息:
+---------+---------+------------+----------+
| 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
但是,我不知道如何编写此查询。如果你这样做,你的帮助将不胜感激:-)