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

咨询:判断日期是否在过去12个月的SQL语句是否有效

判断日期是否处于过去12个月的SQL逻辑修正

你的这段SQL代码逻辑不成立,问题出在BETWEEN的参数顺序上:BETWEEN要求第一个参数必须小于等于第二个参数,而你把当前日期getdate()放在了前面,一年前的日期dateadd(day, -365, getdate())放在后面,后者比前者小,所以这个条件永远不会匹配到任何数据,最终返回的全是false。

修正后的写法

方式一:调整BETWEEN参数顺序

case when lost_renewal_start_date between dateadd(day, -365, getdate()) and getdate()
     then true
     else false 
end as churned_within_last_12_months

方式二:用明确的比较运算符(更直观)

case when lost_renewal_start_date >= dateadd(day, -365, getdate()) 
     and lost_renewal_start_date <= getdate()
     then true
     else false 
end as churned_within_last_12_months

更精准的优化建议

如果要严格匹配“过去12个月”(比如去年今日到今日),用dateadd(year, -1, getdate())替代减365天会更准确,能自动处理闰年的366天情况,避免日期偏差:

case when lost_renewal_start_date between dateadd(year, -1, getdate()) and getdate()
     then true
     else false 
end as churned_within_last_12_months

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:06:19