这是 PL-SQL 中的一个解决方案:DB Fiddle Example
-- select based on runtime calculation
select a.last_active_date
, case
when (sysdate - a.last_active_date) <= 30 then 'Inactive 30 Days or Less'
when (sysdate - a.last_active_date) <= 60 then 'Inactive 30-60'
when (sysdate - a.last_active_date) <= 120 then 'Inactive 60-120'
else 'Inactive 120+ Days'
end Inactivity
from demo a
order by a.last_active_date desc
这是 T-SQL 中的答案:DB Fiddle Example
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
函数的重用应该允许缓存结果,因此应该节省一些计算开销。