Skip to content
Advertisement

Select query to show missing values per day as 0

I have one table with product id’s and another with daily data for these products. When there is no data I want to return 0 instead of no value at all. I tried using a left join but this doesn’t give the resultset I want since the table I can join on has product id’s only, not per day.

I guess I have to generate a table first with all products for all dates and then join my data on that. Not sure how to construct this though.

Example of the products table:

example of the daily data:

Result I’m looking for:

Advertisement

Answer

You can cross join to get the rows and then left join to bring in the data you want:

If there are dates that are not in the table, you can generate the dates using generate_series():

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