2012-05-02 70 views
0

我要計算每個用戶形式交往的數量,每天如下表:使用日期範圍表中也可以返回空結果

+---------+---------+------------+ 
| 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 | 
+---------+---------+------------+ 

所需outpur是:

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 | 
+---------+------------+ 

不過,我不知道如何根據使用該表與第一一個得到我需要的結果集。你做?

回答

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

+0

謝謝你,這真是太棒了:-) – Pr0no

相關問題