如何用具有相同条件和diff结果的多个条件进行解码

时间:2014-11-20 17:23:27

标签: sql oracle

我有一个问题,我如何评估一个sql,当id = 5时,在“目录服务”的情况下,它应该将attr_1作为输出并且id = 5和'Long Roaming'它应该给attr_35 / 60。

sum(decode(id,1,attr_35 / 60,
        5,'Long Roaming',attr_35/60,
        5,'Directory Assistance',attr_1))total


with ce as 
(
select case
    when id = 1 and attr_31 like 'Roam%' 
         then 'A1'
    when id = 5 and attr_30 like 'Dir%' and attr_31 like 'Standard%'
        then 'Directory Assistance'
    when id = 5 and attr_30 like 'Dir%' and attr_31 like 'Roam%'
         then 'Directory Assistance Roaming'
    when id = 5 and attr_30 like 'Long Distance%' and attr_31 like 'Roam%'
        then 'Long Roaming' 
    end usagetype

    , sum(decode(id,1,attr_35 / 60, 5,attr_35/60)) total
    from table
      where ce.account_num in ('A4','A5','A6')

    group by
    case
     when id = 1 and attr_31 like 'Roam%'
        then 'A1'
    when id = 5 and attr_30 like 'Dir%' and attr_31 like 'Standard%'
        then 'Directory Assistance'
    when id = 5 and attr_30 like 'Dir%' and attr_31 like 'Roam%'
        then 'Directory Assistance Roaming'
    when id = 5 and attr_30 like 'Long Distance%'and attr_31 like 'Roam%'
        then 'Long Roaming' 
    end
    )
select usagetype,total from ce

1 个答案:

答案 0 :(得分:0)

首先,我将封装案例逻辑以及您在CTE中可能需要的任何其他列:

with ce as 
(
    select 

    case
      when id = 1 and attr_31 like 'Roam%' 
         then 'A1'
      when id = 5 and attr_30 like 'Dir%' and attr_31 like 'Standard%'
        then 'Directory Assistance'
      when id = 5 and attr_30 like 'Dir%' and attr_31 like 'Roam%'
         then 'Directory Assistance Roaming'
      when id = 5 and attr_30 like 'Long Distance%' and attr_31 like 'Roam%'
        then 'Long Roaming'
      else '-' 
    end usagetype

    , id
    , attr_30
    , attr_31
    , attr_35

    from table
    where ce.account_num in ('A4','A5','A6')
)

然后,在CTE上执行group by(这避免了必须写两次CASE逻辑): -

select 
usagetype 
-- , <sum term will go here>
from ce group by usagetype

第三,由于解码一次只能处理一个列/值,因此需要第二个case

select 

     usagetype 
   , sum(case 
       when id = 1 then
           attr_35 / 60
        when id = 5 and usagetype = 'Long Roaming' then
           attr_35 / 60
        when id = 5 and usagetype = 'Directory Assistance' then
           attr_1
        else
           0
      end) as total_result

from ce group by usagetype

然后,您可以在案例中合并第一个和第二个术语:

select 

     usagetype 
   , sum(case 
       when id = 1 or (id = 5 and usagetype = 'Long Roaming') then
           attr_35 / 60
        when id = 5 and usagetype = 'Directory Assistance' then
           attr_1
        else
           0
      end) as total_result

from ce group by usagetype