咨询:判断日期是否在过去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
相关产品推荐
相关产品推荐

