2010-05-10 20 views
5

Sto tentando di creare l'istruzione SELECT con una clausola GROUP BY, che dovrebbe restituire "valori predefiniti".SQL GROUP BY con "valori predefiniti"

Immaginate la seguente semplice tabella di MySQL:

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

La tabella contiene solo un record:

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

dopo reparti Sto eseguendo la seguente query 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`); 

E ottieni il risultato previsto:

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

Tuttavia, vorrei che il set di risultati simile al seguente:

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

E 'possibile ottenere questo comportamento?

+2

Ci sono parecchi duplicati con questo stesso tema, ad esempio http://stackoverflow.com/questions/400759/sql-group-by-date-but-get-dates-wo-rec ords-too – Unreason

risposta

3

Si potrebbe costruire una tabella temporanea delle date valide nella gamma e poi incorporare che nella vostra interrogazione - che è l'unica via da seguire che posso subito vedere ...

Martin

1

Come Martin Detto questo, la soluzione migliore è creare una tabella temporanea con date.

Poi c'è 2 approcci:

  • ti unisci a una esterna con quella tabella temporanea e fare un group by sul risultato, OR

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