2010-05-10 79 views
5

我試圖用GROUP BY子句創建SELECT語句,該語句應返回「默認值」。具有「默認值」的SQL GROUP BY

想象一下下面這個簡單的MySQL表:

CREATE TABLE `tracker` (
    `id` INTEGER PRIMARY KEY auto_increment, 
    `date` DATETIME NOT NULL, 
    `customer_id` INTEGER NOT NULL 
); 

的表只包含一個記錄:

INSERT INTO `tracker` (`date`, `customer_id`) VALUES('2010-05-03', 1); 

後我執行下面的SQL查詢病房:

SELECT DATE(`date`), COUNT(customer_id) FROM tracker 
WHERE DATE(`date`) >= '2010-05-01' AND DATE(`date`) <= '2010-05-05' 
GROUP BY DATE(`date`) ORDER BY DATE(`date`); 

並獲得預期結果集:

+----+---------------------+-------------+ 
| id | date    | customer_id | 
+----+---------------------+-------------+ 
| 1 | 2010-05-10 00:00:00 |   1 | 
+----+---------------------+-------------+ 

不過,我想結果集是這樣的:

+--------------+--------------------+ 
| DATE(`date`) | COUNT(customer_id) | 
+--------------+--------------------+ 
| 2010-05-01 |     0 | 
| 2010-05-02 |     0 | 
| 2010-05-03 |     1 | 
| 2010-05-04 |     0 | 
| 2010-05-05 |     0 | 
+--------------+--------------------+ 

是否有可能實現這一行爲呢?

+2

有相同的主題有相當多的重複,例如http://stackoverflow.com/questions/400759/sql-group-by-date-but-get-dates-wo-rec ORDS太 – Unreason 2010-05-10 10:26:00

回答

3

你可以建立在範圍內的有效日期的臨時表,然後將此主題融入您的查詢 - 這是關於前,我馬上就可以看到的唯一途徑...

馬丁

1

正如馬丁說,最好的解決方案是創建一個包含日期的臨時表。

然後是2點的方法:

  • 請與臨時表外連接,並做結果group by,或

  • group by原始表+ UNION select date,0 as count from date_table d where not exists (select 1 from customer c where c.date=d.date)