Let's say I need a query to see sales results by Month and I want the result-set to include results for each month whether there were any sales in that month or not.
And let's say my table "sales" has the columns "sales_date" and "sales_amount" and I want a result-set to look like:
Jan, 100.00
Feb, 240.00
Mar, 0.00
Apr, 430.00
So, if I want to sum the values by month and there aren't any records for Mar, I still want to see a result for Mar that's 0. How would I do that?
Best Answer
The usual way to get a series in postgres is with generate_series. This function produces a series of integers or timestamps - you can use either but assuming your 'dates' are really
timestamptz
, here's how you might go about it if you are on 8.4 or above:testbed:
query:
result:
--edit: a bit of extra detail on the query:
produce a summary of sales by month (but no month present if no sales):
which could alternatively be written as:
produce an unbroken series of months (without sales) from the minimum to the maximum:
outer join the unbroken series to the summary of sales by month to produce an unbroken series with sales (or
null
sales if no sales present):for the months with
null
sales, change thenull
to a0
: