计算(次日)16:00之后发布的消息的日期

时间:2012-05-02 18:42:53

标签: mysql sql

考虑下表:

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

我想计算每天的邮件数量,但是今天16:00之后的邮件必须计入第二天:   - msg 1在2011-01-22的16:00之前写入,因此count_for是(同一天)2011-01-22   - msg 2在2011-01-23的16:00之后写入,因此count_for是(第二天)2011-01-24

显然,我手动完成了前5个。我的问题是:我可以使用什么查询自动执行此操作(在MySQL中)?

2 个答案:

答案 0 :(得分:2)

这样的东西
SELECT count(msg_id), if(_time >= '16:00:00', _date + INTERVAL 1 DAY, _date) AS effective_date
FROM yourtable
GROUP BY effective_date

应该这样做。

答案 1 :(得分:1)

SELECT IF(_time < '16:00:00', _date, ADDDATE(_date, 1)) AS d, COUNT(*)
FROM `table`
GROUP BY d