添加类似的IFS函数以查询子查询(oracle sql)

时间:2015-08-07 18:36:13

标签: sql oracle

这是我的查询的一部分。如果影响标签为1且小时>我想添加另一个名为Missed的列。 8 - >错过,影响2小时> 14 - >错过,影响3小时> 80 - >错过。请帮忙。谢谢!

long

1 个答案:

答案 0 :(得分:0)

我会使用“with”子句稍微重写一下,但那只是我.. :)你可能需要另一层来使用已计算的列...

尝试这样的事情:

  with w_o as (
     select 
        ,to_char(create_date,'yyyy/mm/dd hh24:mi:ss') as create_datetime
        ,to_char(resolved_date,'yyyy/mm/dd hh24:mi:ss') as resolved_datetime
        ,status
        ,(case impact_label
          when '1 - ' then '1'
          when '2 - ' then '2'
          when '3 - ' then '3'
          when '4 - ' then '4'
          when '5 - ' then '5'
          else null
          end) as impact_label
        from   
          table
        ),
     w_sub as (
           select
              o.create_datetime
             ,o.resolved_datetime
             ,24 * (to_date(resolved_datetime, 'yyyy/mm/dd hh24:mi:ss') 
                        - to_date(create_datetime, 'yyyy/mm/dd hh24:mi:ss')) as hours 
             ,o.item
             ,o.impact_label
           from w_o
        )
  select create_datetime,
         resolved_datetime,
         hours,
         item,
         impact_label,
         case when impact_label = '1' and hours > 8
                 then 'missed'
              when impact_label = '2' and hours > 14
                 then 'missed'
              when impact_label = '3' and hours > 80
                 then 'missed'
              else
                 'hit?'
           end  missed
  /

这是新的部分,休息与你拥有的相同,只是重新安排成WITH子句..;)

         case when impact_label = '1' and hours > 8
                 then 'missed'
              when impact_label = '2' and hours > 14
                 then 'missed'
              when impact_label = '3' and hours > 80
                 then 'missed'
              else
                 'hit?'
           end  missed

你也可以使用OR组合case子句,但是,这可能更清楚,阅读和遵循......所以无论如何......