SQL GROUP BY with "default values"
        Posted  
        
            by Christoph Schiessl
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Christoph Schiessl
        
        
        
        Published on 2010-05-10T10:15:50Z
        Indexed on 
            2010/05/10
            10:24 UTC
        
        
        Read the original article
        Hit count: 324
        
I'm trying to create SELECT statement with a GROUP BY clause, which should return "default values".
Imagine the following simple MySQL table:
CREATE TABLE `tracker` (
  `id` INTEGER PRIMARY KEY auto_increment,
  `date` DATETIME NOT NULL,
  `customer_id` INTEGER NOT NULL
);
The table contains only one record:
INSERT INTO `tracker` (`date`, `customer_id`) VALUES('2010-05-03', 1);
After wards I'm executing the following SQL query:
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`);
And get the expected result set:
+----+---------------------+-------------+
| id | date                | customer_id |
+----+---------------------+-------------+
|  1 | 2010-05-10 00:00:00 |           1 |
+----+---------------------+-------------+
However, I would like the result set to look like this:
+--------------+--------------------+
| 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 |
+--------------+--------------------+
Is it possible to achieve this behavior?
© Stack Overflow or respective owner