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

如何声明日期列表并在SQL WHERE子句中批量查询月度数据

批量查询多个月末日期对应的当月审批条目

方法1:用表变量存储目标日期(灵活易维护)

通过表变量存储所有需要查询的月末日期,再关联原表筛选对应数据:

-- 声明表变量存放多个月末日期
declare @target_dates table (target_date date);
-- 插入需要查询的日期,可按需增减
insert into @target_dates (target_date)
values ('2024-08-31'), ('2024-07-31');

-- 关联查询获取每个日期对应的当月审批条目
select 
    x.*,
    td.target_date as 查询月末日期 -- 可选,用于区分不同月份的结果
from x
inner join @target_dates td 
    on x.ReportDate = td.target_date
    and x.ApprovedDate <= td.target_date
    and x.ApprovedDate > eomonth(td.target_date, -1);

方法2:直接用VALUES子句生成日期列表(简洁高效)

如果只是一次性查询固定日期,无需单独维护表变量,直接在查询中生成日期列表:

select 
    x.*,
    td.target_date as 查询月末日期
from x
inner join (
    -- 这里列出所有需要查询的月末日期
    values ('2024-08-31'), ('2024-07-31')
) as td(target_date)
    on x.ReportDate = td.target_date
    and x.ApprovedDate <= td.target_date
    and x.ApprovedDate > eomonth(td.target_date, -1);

注意事项

  • 建议使用YYYY-MM-DD标准日期格式,避免因数据库区域设置导致的日期解析错误
  • 如果数据集较大,确保ReportDate和ApprovedDate字段创建了合适的索引,提升查询效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 03:45:08