我想计算下表中每个用户每天的消息数:
+---------+---------+------------+
| 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 |
+---------+------------+
但是,我不知道如何按照第一个使用这个表来获得我需要的结果集。你?