简体   繁体   中英

I want to fetch the data where I will put the date and I will get data from last three years to the entered date

imagine if I put the date 27th Jan 2022 then I should get all the records from 26th Jan 2019 till 27th Jan 2022.

There are a couple of ways to do this. One caveat is how you are defining three years:

select '2022-01-27'::date - interval '3 years';
      ?column?       
---------------------
 2019-01-27 00:00:00

or as you have it:

2019-01-26 to 2022-01-27 .

Using your definition:

SELECT * FROM some_table WHERE date_fld BETWEEN '2019-01-26' and '2022-01-27';

--Using a date range

select * from  some_table where date_fld <@ daterange('2019-01-26', '2022-01-27', '[]');
 t
--or
select * from some_table where  date_fld <@ daterange('2019-01-26', '2022-01-28');
t

By default date ranges are exclusive on the upper bound, that is why you need to include either the '[]' or bump the upper bound up one date(which is actually what the '[]' does).

For more information on ranges Ranges and Range operators

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