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

SQL Server 2016日期查询异常:近3个月数据少返回1天

SQL Server 2016查询近3个月日期少一天的解决办法

问题根源

你使用的getdate()返回的是带时分秒的完整datetime值,比如当前时间是2023-03-23 14:30:00,dateadd(month, -3, getdate())会得到2022-12-23 14:30:00。这就导致:

  • 2022-12-23当天所有时间早于14:30:00的记录被过滤,看起来像是少了这天的数据
  • 当前日期(2023-03-23)中时间早于当前时刻的记录也会被排除

解决方法

核心是截断getdate()的时间部分,让起始条件变成目标日期的零点,以下是两种实用写法:

方法1:强制转换为date类型

select * from TABLE where DATE_COLUMN >= dateadd(month, -3, cast(getdate() as date))

cast(getdate() as date)会把当前时间转为不带时分秒的date类型(如2023-03-23),再往前推3个月得到2022-12-23,此时所有DATE_COLUMN大于等于2022-12-23 00:00:00的记录都会被包含。

方法2:用datefromparts构造纯日期

select * from TABLE where DATE_COLUMN >= dateadd(month, -3, datefromparts(year(getdate()), month(getdate()), day(getdate())))

datefromparts通过年、月、日参数构造纯日期值,效果和方法1完全一致,适合需要明确拆分日期组件的场景。

快速验证

可以单独运行以下语句对比结果,直观看到时间部分的影响:

-- 带时间的起始值
select dateadd(month, -3, getdate())
-- 纯日期的起始值
select dateadd(month, -3, cast(getdate() as date))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 11:02:17