You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何筛选包含2024年的日期范围?PostgreSQL查询问题

需求与SQL修正方案

需求描述

需要筛选出起始年份为2024年的所有记录,具体判断规则如下:

  • 符合条件的时间范围示例:
    [2024-01-01, 2024-02-10) <- 符合(起始于2024年)
    [2024-12-29, 2025-01-10) <- 符合(起始于2024年)
    
  • 不符合条件的示例:
    [2025-01-15, 2025-02-02) <- 不符合(起始年份非2024)
    

原代码问题

当前使用的代码是判断时间范围完全包含在2024年全年内,无法覆盖起始于2024年但跨到2025年的情况:

select time_range
from holidays
where time_range::daterange <@ daterange('2024-01-01', '2024-12-31', '[)')

修正后的代码

要筛选起始年份为2024的记录,需要针对时间范围的起始日期提取年份进行判断,有两种实现方式:

方式一:提取起始日期的年份

select time_range
from holidays
where extract(year from lower(time_range::daterange)) = 2024

方式二:匹配年份起始日期

select time_range
from holidays
where date_trunc('year', lower(time_range::daterange)) = '2024-01-01'::date

这两种方式都能准确筛选出起始年份为2024的所有记录,包括跨年度的时间范围。

内容的提问来源于stack exchange,提问作者locklock123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 08:12:44