Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have GROUP BY and COUNT include zero sums?

Tags:

sql

sqlite

I have SQL like this (where $ytoday is 5 days ago):

$sql = 'SELECT Count(*), created_at FROM People WHERE created_at >= "'. $ytoday .'" AND GROUP BY DATE(created_at)';

I want this to return a value for every day, so it would return 5 results in this case (5 days ago until today).

But say Count(*) is 0 for yesterday, instead of returning a zero it doesn't return any data at all for that date.

How can I change that SQLite query so it also returns data that has a count of 0?

like image 933
JBurace Avatar asked May 14 '12 15:05

JBurace


People also ask

How do you include zeros in a COUNT aggregate?

A simple JOIN will not return the desired result; it will show only those buyers that have one or more service appointments. To include zeros resulting from COUNT() , you'll have to use LEFT JOIN or RIGHT JOIN .

Can we use COUNT and GROUP BY together?

The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.

How do I COUNT 0 in SQL?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

Can we use GROUP BY without COUNT?

Using COUNT, without GROUP BY clause will return a total count of a number of rows present in the table. Adding GROUP BY, we can COUNT total occurrences for each unique value present in the column.


1 Answers

Without convoluted (in my opinion) queries, your output data-set won't include dates that don't exist in your input data-set. This means that you need a data-set with the 5 days to join on to.

The simple version would be to create a table with the 5 dates, and join on that. I typically create and keep (effectively caching) a calendar table with every date I could ever need. (Such as from 1900-01-01 to 2099-12-31.)

SELECT
  calendar.calendar_date,
  Count(People.created_at)
FROM
  Calendar
LEFT JOIN
  People
    ON Calendar.calendar_date = People.created_at
WHERE
  Calendar.calendar_date >= '2012-05-01'
GROUP BY
  Calendar.calendar_date
like image 60
MatBailie Avatar answered Sep 26 '22 02:09

MatBailie