2014-11-20 43 views
1

我有一個問題,我如何評估一個SQL,當ID = 5的情況下,'目錄援助'它應該得到attr_1作爲輸出和ID = 5和'長漫遊'它應該給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 

回答

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執行組(這樣就不必寫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