使用daterange表也返回空结果集

时间:2012-05-02 20:47:30

标签: mysql sql

我想计算下表中每位用户每天的消息数量:

+---------+---------+------------+
| msg_id  | user_id | m_date     |
+-------------------+------------+
|   1     | 1       | 2011-01-21 |
|   2     | 1       | 2011-01-23 |
|   3     | 1       | 2011-01-23 |
|   5     | 2       | 2011-01-23 |
|   6     | 2       | 2011-01-24 |
|   8     | 1       | 2011-01-23 |
|   9     | 2       | 2011-01-23 |
|  10     | 1       | 2011-01-24 |
+---------+---------+------------+

期望的外包将是:

1 2011-01-21 1
2 2011-01-21 0
1 2011-01-22 0
2 2011-01-22 0
1 2011-01-23 3
2 2011-01-23 2
1 2011-01-24 1
2 2011-01-24 1

我使用以下查询:

SELECT m_date, COUNT(msg_id ) AS volume
FROM messages
GROUP BY user_id, m_date
ORDER BY user_id, m_date ASC 

但是在这里,结果集中省略了体积为零的日期:

1 2011-01-21 1
1 2011-01-23 3
2 2011-01-23 2
1 2011-01-24 1
2 2011-01-24 1

但是,我希望结果集中的那些日子。所以我理解我应该使用一个“日期范围”表,其中包含我想要结果的所有日期:

+---------+------------+
| date_id | d_date     |
+---------+------------+
| 1       | 2011-01-21 |
| 2       | 2011-01-22 |
| 3       | 2011-01-23 |
| 4       | 2011-01-24 |
+---------+------------+

但是,我不知道如何根据第一个使用此表来获取我需要的结果集。你呢?

1 个答案:

答案 0 :(得分:2)

这可以使用交叉连接来完成:

SELECT user_id, d_date,
       COUNT(CASE WHEN messages.m_date = d.d_date then 1 end) Volume
FROM messages
CROSS JOIN datetable d
GROUP BY messages.user_id, d.d_date
ORDER BY messages.user_id, d.d_date ASC

Sql Fiddle demo