Skip to content
Advertisement

Postgresql Serial Daily Count of Records

I am trying to get a total count of records from 1st Jan till date, without skipping dates and returning 0 for dates that have no records.

I have tried the following: orders is an example table and orderdate is a timestamp column

The issue is that dates are skipped. yet if i execute:

i get the right series with no dates skipped.

Advertisement

Answer

The where condition should belong to the on clause of the left join, ie this:

Should be written:

Notes:

  • you don’t actually need a cte here, you can put generate_series() directly in the from clause

  • the date join condition can be optimized to an index-friendly expression that avoids date_trunc()

  • table aliases make the query easier to read and write

You could write the query as:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement