我正在尝试编写一个案例陈述,它将根据当前系统日期过滤一系列日期。我需要30天前到现在,30-60天前和60-120天之前的范围,所有这些都基于系统日期。这就是我不远处证明不成功的原因:
(case
when a.last_active_date between sysdate and sysdate-30 then 'Inactive 30 Days or Less'
when a.last_active_date between sysdate-30 and sysdate-60 then 'Inactive 30-60'
when a.last_active_date between sysdate-60 and sysdate - 120 then 'Inactive 60-120'
else 'Inactive 120+ Days'
end) Inactivity,
有关我应如何处理的任何建议吗?
答案 0 :(得分:0)
以下是T-SQL中的答案:
select a.last_active_date
, case
when getutcdate() - a.last_active_date <= 30 then 'Inactive 30 Days or Less'
when getutcdate() - a.last_active_date <= 60 then 'Inactive 30-60'
when getutcdate() - a.last_active_date <= 120 then 'Inactive 60-120'
else 'Inactive 120+ Days'
end Inactivity
from @t a
order by a.last_active_date desc
以下是使用测试数据设置上述示例的代码:
declare @t table (last_active_date datetime)
insert @t select getutcdate()
union select getutcdate()-29
union select getutcdate()-30
union select getutcdate()-31
union select getutcdate()-59
union select getutcdate()-60
union select getutcdate()-61
union select getutcdate()-119
union select getutcdate()-120
union select getutcdate()-121
这样做的好处是重用getutcdate() - a.last_active_date
函数应该允许缓存结果,所以应该节省一些计算开销。