我試圖用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 |
+--------------+--------------------+
是否有可能實現這一行爲呢?
有相同的主題有相當多的重複,例如http://stackoverflow.com/questions/400759/sql-group-by-date-but-get-dates-wo-rec ORDS太 – Unreason 2010-05-10 10:26:00