2014-05-20 62 views
1

這個post讓我開始了。使用和理解空列的pivot()

with inventory_row as 
(select 1 as item_id, '2014AA' as batch_year, 'AA' as batch_code from dual union all 
select 1 as item_id, '2012BB' as batch_year, 'BB' as batch_code from dual union all 
select 1 as item_id, '2012CC' as batch_year, 'CC' as batch_code from dual union all 
select 2 as item_id, '2012BB' as batch_year, 'BB' as batch_code from dual union all 
select 3 as item_id, '2014AA' as batch_year, 'AA' as batch_code from dual 
) 
select * from (
    select item_id, 
     batch_year, 
     batch_code 
from inventory_row   
where (batch_year = '2014AA' and batch_code='AA') 
     or 
     (batch_year = '2012BB' and batch_code='BB')   
)     
--pivot (max(item_id) for batch_year in ('2014AA' as batch_1, '2012BB' as batch_2)) 

預期的效果

打開本

ID  BATCH_YR CODE 
1  2014AA AA 
1  2012BB BB 
2  2012BB BB 
3  2014AA AA 

進入這

ITEM_ID BATCH_14 CODE BATCH_12 CODE 
1  2014AA  AA  2012BB  BB 
2  null  null 2012BB  BB 
3  2014AA  AA  null  null 

回答

1

嘗試此查詢:

SELECT ID as ITEM_ID, 
     MAX(CASE WHEN SUBSTR(BATCH_YR,1,4) = '2014' 
       THEN BATCH_YR 
       ELSE NULL 
      END) as BATCH_14, 
     MAX(CASE WHEN SUBSTR(BATCH_YR,1,4) = '2014' 
       THEN CODE 
       ELSE NULL 
      END) as CODE_14, 
     MAX(CASE WHEN SUBSTR(BATCH_YR,1,4) = '2012' 
       THEN BATCH_YR 
       ELSE NULL 
      END) as BATCH_12, 
     MAX(CASE WHEN SUBSTR(BATCH_YR,1,4) = '2012' 
       THEN CODE 
       ELSE NULL 
      END) as CODE_12 
FROM T 
GROUP BY ID 

SQLFiddle demo

1

正如原問題的意見建議使用支點我已經塞進查詢到樞軸查詢。如果min()是從業務角度在查詢中使用的合適聚合,則需要驗證它。

對於給定的數據集,它會產生預期的結果。

with inventory_row as 
(select 1 as item_id, '2014AA' as batch_year, 'AA' as batch_code from dual union all 
select 1 as item_id, '2012BB' as batch_year, 'BB' as batch_code from dual union all 
select 1 as item_id, '2012CC' as batch_year, 'CC' as batch_code from dual union all 
select 2 as item_id, '2012BB' as batch_year, 'BB' as batch_code from dual union all 
select 3 as item_id, '2014AA' as batch_year, 'AA' as batch_code from dual 
) 
select item_id, 
min (Y2012_BATCH) BATCH_12, 
min(Y2012_CODE) CODE_12, 
min(Y2014_BATCH) BATCH_14, 
min(Y2014_CODE) CODE_14 
from 
(
select item_id, 
     batch_year, 
     batch_code, 
     'CODE'||substr(batch_year,1,4) col_c 
from inventory_row 
) 
pivot 
(min(batch_year) as batch, 
min(batch_code) as code 
for col_c in ('CODE2012' as Y2012 ,'CODE2014' as Y2014) 
) 
group by item_id 
order by item_id 

結果:

ITEM_ID BATCH_12 CODE_12 BATCH_14 CODE_14 
---------- -------- ------- -------- ------- 
     1 2012BB BB  2014AA AA  
     2 2012BB BB      
     3     2014AA AA 
+0

奧拉夫:歡迎來到SO。感謝您的迴應。 – zundarz