【问题标题】:Find the date range between the given year and month查找给定年份和月份之间的日期范围
【发布时间】:2023-03-23 15:11:02
【问题描述】:

我有下表的日期范围:

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 将介于上述范围之间。

试一试

select * 
from stf
where to_char(now(),'YYYY-MM') between to_char(d1,'YYYY-MM') and to_char(d2,'YYYY-MM');

输出:

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))

输出:

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

【问题讨论】:

    标签: sql postgresql datetime where-clause postgresql-12


    【解决方案1】:

    您可以只检查当前月份的开始是否属于该范围:

    select *
    from stf
    where date_trunc('month', current_date) between d1 and d2
    

    【讨论】:

    • 缺少此范围2020-11-25 2020-11-25。对不起,我的不好,没有在预期的结果中提到。现已编辑。
    • 我觉得应该没问题to_char(now(),'YYYYMM') between to_char(d1,'YYYYMM') and to_char(d2,'YYYYMM')吧?
    • @MAK:是的。或date_trunc('month', current_date) between date_trunc('month', d1) and date_trunc('month', d2)
    猜你喜欢
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 2020-12-07
    • 2012-09-24
    • 1970-01-01
    相关资源
    最近更新 更多