1

我正在尝试编写一个案例语句,它将根据当前系统日期过滤一系列日期。我需要从 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,

关于我应该如何处理这个问题的任何建议?

4

1 回答 1

1

这是 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函数的重用应该允许缓存结果,因此应该节省一些计算开销。

于 2012-11-20T21:15:29.173 回答