2016-07-12 84 views
0

我有一組數據:的Oracle SQL樞軸與排除

SELECT * FROM costings 

輸出:

section von   part price 
5  2013000043 3019 -15000 
5  2014000041 1547 18000 
5  2014000041 3019 -15000 
5  2014000071 1547 18000 
5  2014000071 3019 -15000 
5  2016000018 1547 12000 
5  2016000018 3019 -10000 
5  2014000081 1549 3244.8 
5  2014000081 3019 -1474 
5  2015000040 1549 3244.8 
5  2015000040 3019 -1474 
5  2016000021 1549 2506.8 
5  2016000021 3019 -1474 
6  2013000069 1566 5760 
6  2013000069 3013 -4800 
6  2013000128 1566 7200 
6  2013000128 3013 -6000 
6  2014000060 1566 5760 

我想輸出使用旋轉這樣的數據:

section 1547 1549 1566 
5  -40000 -4422 null 
6  null null -10800 

現在,期望值金額背後的邏輯是每von您有多個part數字。

因此以2014000041爲例,這有1547 & 3019

我要的是part數與15開始被樞軸頭,而是SUM只總結價格在part15開始。

回答

2

如果你知道,以「15」開頭的值,那麼一個想法是預聚集一起section/von,然後再彙總結果:

select section, 
     sum(case when part15 = '1547' then price_not15 end) as part_1547, 
     sum(case when part15 = '1549' then price_not15 end) as part_1549, 
     sum(case when part15 = '1566' then price_not15 end) as part_1566 
from (select section, von, 
      max(case when part like '15%' then part end) as part15, 
      sum(case when part not like '15%' then price end) as price_not15 
     from costings 
     group by section, von 
    ) c 
group by section; 

這是假設只存在一部分以15開頭,每個section/von組合。