【问题标题】:Range of dates based on system date within a case statement基于案例陈述中系统日期的日期范围
【发布时间】:2019-08-29 16:09:39
【问题描述】:

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

关于我应该如何处理这个问题有什么建议吗?

【问题讨论】:

  • 除了这些范围重叠,因为between 包含在内,查询不成功的原因是什么?
  • 你为什么要在SQL中这样做,这种事情通常在应用层处理更好。另外,这两个不同的标签是怎么回事——它是哪个 RDBMS?
  • @MichaelFredrickson - 除了重叠之外,它没有正确过滤
  • @Clockwork-Muse - 我正在将原始数据加载到 Spotfire 中,我不确定我还能如何做到这一点。这是一个 oracle 数据库。

标签: sql oracle11g


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

【讨论】:

  • 缓存结果 per-CASE 语句,也许(对 SQL Server 的了解不够肯定)。用于可索引搜索的缓存,不。无论如何,您都在输出所有行,所以这并不像其他情况那么重要。
  • 同意它将(可能)仅按行缓存,因此不会产生很大的不同,但任何优化都会有所帮助。
猜你喜欢
  • 2017-07-03
  • 1970-01-01
  • 2023-01-13
  • 2015-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多