You need to enable JavaScript to run this app. SQL Server中如何判断指定日期是否处于同ID不同行的两个日期之间
优惠活动
大模型
产品
解决方案
定价
更多

SQL Server中如何判断指定日期是否处于同ID不同行的两个日期之间

实现方案

实现逻辑

先按PlanEffectiveDate升序对同ID的记录排序,取第1条的PlanTerminationDate作为区间左边界、第2条的PlanEffectiveDate作为区间右边界,再判断同ID的EndDate是否落在该区间内即可。

通用SQL写法(支持窗口函数的现代数据库,如MySQL 8.0+、PostgreSQL、SQL Server等)

WITH ranked_plans AS (
    SELECT 
        ID,
        PlanTerminationDate,
        -- 取同ID下一条记录的PlanEffectiveDate
        LEAD(PlanEffectiveDate) OVER (PARTITION BY ID ORDER BY PlanEffectiveDate ASC) AS next_plan_effective_date,
        EndDate,
        -- 给同ID的记录排序,取第1条即可完成判断
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY PlanEffectiveDate ASC) AS rn
    FROM your_table_name -- 替换为实际表名
)
SELECT 
    ID,
    EndDate,
    PlanTerminationDate AS first_record_termination_date,
    next_plan_effective_date AS second_record_effective_date,
    CASE WHEN EndDate BETWEEN PlanTerminationDate AND next_plan_effective_date THEN '是' ELSE '否' END AS is_in_range
FROM ranked_plans
WHERE rn = 1
-- 如需查询特定ID,取消注释下方代码并替换ID值
-- AND ID = 11
;

老版本MySQL兼容写法(不支持窗口函数)

SELECT 
    t1.ID,
    t1.EndDate,
    t1.PlanTerminationDate AS first_record_termination_date,
    t2.PlanEffectiveDate AS second_record_effective_date,
    CASE WHEN t1.EndDate BETWEEN t1.PlanTerminationDate AND t2.PlanEffectiveDate THEN '是' ELSE '否' END AS is_in_range
FROM (
    SELECT ID, MIN(PlanEffectiveDate) AS first_effective_date, EndDate 
    FROM your_table_name -- 替换为实际表名
    GROUP BY ID, EndDate
) t_min
INNER JOIN your_table_name t1 
    ON t_min.ID = t1.ID AND t_min.first_effective_date = t1.PlanEffectiveDate
INNER JOIN your_table_name t2 
    ON t_min.ID = t2.ID AND t2.PlanEffectiveDate > t_min.first_effective_date
-- 如需查询特定ID,取消注释下方代码并替换ID值
-- WHERE t1.ID = 11
;

注意事项

  • 若表中日期以字符串格式存储,比较前需先转为日期类型,例如MySQL使用STR_TO_DATE(日期字段, '%m/%d/%Y')完成格式转换
  • 上述写法默认每个ID至少有2条记录,如需保留记录数不足2条的ID,可将INNER JOIN改为LEFT JOIN
  • 示例数据运行结果:ID 11、ID 12的EndDate均落在对应区间内,判断结果为「是」

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 06:24:04