简体   繁体   中英

Date range in PostgreSQL

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM