4

I have a query to retrieve a total number of events per day between two dates.

SELECT
  DATE_FORMAT(startTime, '%Y%m%d') as day,
  COUNT(0) as numEvents
FROM events
WHERE
  (startTime BETWEEN 20140105000000 AND 20140112235900)
GROUP BY
  day;

This return a list like

day      | numEvents
---------+----------
20140105 | 45
20140107 | 79
20140108 | 12
20140109 | 56

Notice that there are missing days in the result since there are no events in the events table for those days. Is there any way to return 0 values for those days, resulting in:

day      | numEvents
---------+----------
20140105 | 45
20140106 | 0
20140107 | 79
20140108 | 12
20140109 | 56
20140110 | 0
20140111 | 0
20140112 | 0
carexcer
  • 1,407
  • 2
  • 15
  • 27
Christophe Herreman
  • 15,895
  • 9
  • 58
  • 86
  • A few solutions here: http://stackoverflow.com/questions/6310839/sql-group-by-including-empty-rows – JSuar Jan 11 '14 at 15:01

3 Answers3

0

There are quite a few solutions on SO:

One solution is to you another table that contains all possible/relevant dates. One implementation can be found here: https://stackoverflow.com/a/7262803/1085891

This is typically done in data warehouses by having a date dimension that has a list of all possible dates. You do an OUTER JOIN to the date dimension and COALESCE the null values to 0.

If run often, it would be more efficient to store the dates. However, for a quick report you could generate the dates you need and join the output to the table you are searching against.

Community
  • 1
  • 1
JSuar
  • 21,056
  • 4
  • 39
  • 83
0

Try this

SELECT  DATE_FORMAT(startTime, '%Y%m%d') as day, COUNT(DATE_FORMAT(startTime, '%Y%m%d'))
FROM  events 
WHERE
(startTime BETWEEN 20140105000000 AND 20140112235900)
GROUP BY day;
Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
0

You will able to do it if startTime is a foreign_key to another table which have values for every date. This is tipical on multidimensional models of data-warehouses, where you have a date/time dimension and them include all days.

In that case, I think the solution provided by Vigens Kumar would work:

SELECT  DATE_FORMAT(startTime, '%Y%m%d') as day, COUNT(DATE_FORMAT(startTime, '%Y%m%d'))
FROM  events 
WHERE
(startTime BETWEEN 20140105000000 AND 20140112235900)
GROUP BY day;
Community
  • 1
  • 1
carexcer
  • 1,407
  • 2
  • 15
  • 27