2

I have data in my table of the following form:

| date     | type | value |
+----------+------+-------+
|2020-01-01| A    |     29|
|2020-02-01| A    |     32|
|2020-04-01| A    |     56|
|2020-05-01| A    |     78|
|2020-01-01| B    |     12|
|2020-02-01| B    |     89|
|2020-03-01| B    |     44|
|2020-05-01| B    |     33|

Now while querying this data, I want the missing dates to be filled with null values.

In PostgreSQL, I can use generate_series() to create a series of dates and then left join with it. But that only works if I have just a series of dates and values. In this case, since I have two types, I don't really have any missing dates in the series as a whole, but I have missing dates in each group/partition.

Is it possible to use generate_series() with left join to fill rows with null in this case?

1 Answer 1

6

You may cross join with a table which contains all types, and then use the same left join approach you were already considering:

SELECT
    date_trunc('day', cal)::date AS date,
    t1.type,
    t2.value
FROM generate_series
    ( '2020-01-01'::timestamp 
    , '2020-12-31'::timestamp
    , '1 day'::interval) cal
CROSS JOIN (SELECT DISTINCT type FROM yourTable) t1
LEFT JOIN yourTable t2
    ON t2.date = cal.date AND t2.type = t1.type
ORDER BY
    t1.type,
    cal.date;
Sign up to request clarification or add additional context in comments.

1 Comment

Cross join was what I needed, I wasn't aware of such a function. This solution worked for me, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.