I've written a query to retrieve how many website signups I've had every day:
SELECT created, COUNT(id)
FROM signups
GROUP BY created
ORDER BY created desc
However, this only retrieves rows for days where people have actually signed up. If nobody has signed up in a day, I would like to return 0 for that day. Is there a way to do this using SQL or will I have to parse through the results using PHP?
You should create a calendar table in your database (or generate it in a query) and join it with yours then you will get
0
for empty daysHere is a way to make a calendar date in PostgreSQL
You need to make use of a calendar table that has a series of dates and join with it
You can use NULLIF function:
Documentation: http://www.postgresql.org/docs/8.1/static/functions-conditional.html
Assuming
created
to be of typedate
for lack of information.Postgres provides the wonderful
generate_series()
to make this easy:This retrieves minimum and maximum day from your table automatically and provides one row per day in between.