15

When I apply a date range to my query, is there anyway to display the dates used in the date range even if there is no data at those dates?

Suppose I use,

... where date between '1/12/2010' and '31/12/2010' order by date

What I want in my result is to show sum of all amount column until 1/12/2010 on that day even if there is no data for that date and also same for 31/12/2010.

1 Answer 1

27

Join with generate_series() to fill in the gaps.

Example:

CREATE TEMP TABLE foo AS SELECT CURRENT_DATE AS today;
SELECT
    COUNT(foo.*),
    generate_series::date
FROM
    foo
        RIGHT JOIN generate_series('2010-12-18', '2010-12-25', interval '1 day') ON generate_series = today
GROUP BY
    generate_series;

Result:

0,'2010-12-18'
0,'2010-12-19'
1,'2010-12-20'
0,'2010-12-21'
0,'2010-12-22'
0,'2010-12-23'
0,'2010-12-24'
0,'2010-12-25'
Sign up to request clarification or add additional context in comments.

Comments

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.