![](/img/trans.png)
[英]Get all records which falls with in the date range for a given month and year
[英]Find the date range between the given year and month
我有下表的日期范围:
create table stf
(
d1 date,
d2 date
);
insert into stf values
('2020-01-01','2020-12-31'),
('2020-11-25','2020-11-25'),
('2019-01-01','2020-11-29'),
('2020-11-01','2021-01-06'),
('2019-01-23','2021-06-06'),
('2019-01-20','2019-12-30');
我正在寻找当前日期的月份和年份之间的日期范围。
预期结果应该是:对于当前日期
d1 d2
--------------------------
2020-01-01 2020-12-31
2019-01-01 2020-11-29
2020-11-01 2021-01-06
2019-01-23 2021-06-06
2020-11-25 2020-11-25
注意: 2020-11
将在上述范围之间。
尝试 1 :
select *
from stf
where to_char(now(),'YYYY-MM') between to_char(d1,'YYYY-MM') and to_char(d2,'YYYY-MM');
Output:
d1 d2
--------------------------
2020-01-01 2020-12-31
2020-11-25 2020-11-25
2019-01-01 2020-11-29
2020-11-01 2021-01-06
2019-01-23 2021-06-06
尝试 2 :
select *
from stf
where ((date_part('month',now()) between date_part('month',d1) and date_part('month',d2))or date_part('year',now()) between date_part('year',d1) and date_part('year',d2))
Output:
d1 d2
--------------------------
2020-01-01 2020-12-31
2020-11-25 2020-11-25
2019-01-01 2020-11-29
2020-11-01 2021-01-06
2019-01-23 2021-06-06
您可以检查当前月份的开始是否属于该范围:
select *
from stf
where date_trunc('month', current_date) between d1 and d2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.