简体   繁体   中英

How can I change the value for “WHERE startdate >= date” clause and get data for a range of dates?

I am querying a property_table that looks like below, showing between which date to which date the property were active.

fid     startdate   enddate
---     ----------  --------
2588727 2019-01-11  2019-05-09
2591038 2019-01-11  2019-01-18
2587420 2019-03-11  2019-04-09
2592269 2019-03-29  2019-03-09

fid is the flat_id for a house/flat.

I am trying to find out how many flats were active on each day between 2019-03-15 and 2019-04-30 in the below format.

Date        active_count
----------   -----------  
2019-03-15  235631
2019-03-16  234545
2019-03-17  234334
2019-03-29  342123
..
..
2019-04-30  344322

I am able to find active flats on a single day by using the below query. Please help to find for the entire date range as above.

-- Number of flats on '2019-03-20' Date
SELECT COUNT(*)
FROM invent_table 
WHERE startdate <= '2019-03-20' 
AND enddate >= '2019-03-20'

With generate_series() you create the series of the days you are interested in, join to the table and group:

select d.Date, count(i.fid) active_count
from (
 select generate_series(date '2019-03-15', date '2019-04-30', '1 day') as Date
) d left join invent_table i
on d.Date between i.startdate and i.enddate
group by d.Date
order by d.Date

See the demo .

Are your looking for something like this?

SELECT COUNT(*)
FROM invent_table 
WHERE startdate >= '2019-03-15' 
AND enddate <= '2019-04-30'

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