Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date range in PostgreSQL

Tags:

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.

like image 420
Rabin Avatar asked Dec 20 '10 06:12

Rabin


People also ask

How do you select a date range?

In the calendar, click the desired start date, then click the end date. The selected days are highlighted. OR. Enter start and end dates in the Date Range fields.

How do I select data between two dates in PostgreSQL?

Use the PostgreSQL AGE() function to retrieve the interval between two timestamps or dates. This function takes two arguments: the first is the end date and the second is the start date.

What is date data type in PostgreSQL?

The date format for the date data type in PostgreSQL is yyyy-mm-dd . This is the format used for both storing data and for inserting data.

What is range in PostgreSQL?

Range types are a unique feature of PostgreSQL, managing two dimensions of data in a single column, and allowing advanced processing. The main example is the daterange data type, which stores as a single value a lower and an upper bound of the range as a single value.


1 Answers

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'
like image 166
Frank Heikens Avatar answered Oct 07 '22 19:10

Frank Heikens