2015-02-11 33 views
0

我有以下SQL表:選擇數據

MONTH CODE DESCR QTY PRICE 
201401 3641 HO  29  3829 
201401 3641 IL  2  2 
201401 3641 Office 34  43576 
201401 3641 Other 38  424 
201401 3641503 HO  2904 13584 
201401 3641503 IL  2045 2833 
201401 3641503 Office 106  237 
201401 3641503 Other 79  129 
201401 364  HO  37  182 
201401 364  IL  8  9 
201401 364  Office 750  1317 
201401 364  Other 5  6 

從這個表我想創建另一個表看起來像這樣:

MONTH CODE  HO_qty IL+Office_QTY Other_QTY HO_Price IL+Office_Price Other_Price 
201401 3641  29   36(34+2)  38   3829  43578(43576+2) 424 
201401 3641503 2904   2151   79   13584  3070    129 
201401 364  37   758   5   182   1326    6 

在SQL小提琴是這裏:http://sqlfiddle.com/#!2/cf745df/1

任何指針的方法?

回答

2

認爲這可能是你在找什麼:

Select 
MONTH, CODE, 
sum(case when descr in ('Office','IL') then QTY end) as `IL+Office_QTY`, 
sum(case when descr = 'HO' then QTY end) as `HO_qty`, 
sum(case when descr = 'Other' then QTY end) as `Other_QTY`, 

sum(case when descr in ('Office','IL') then PRICE end) as `IL+Office_Price`, 
sum(case when descr = 'HO' then PRICE end) as `HO_Price`, 
sum(case when descr = 'Other' then PRICE end) as `Other_Price` 
from Table1 
group by MONTH, CODE 
+0

感謝。有一會兒,我忘記了病例陳述。 – Morpheus 2015-02-11 01:22:17

+0

這是一種享受! – 2015-02-11 01:24:09