使用和理解pivot()与空列

时间:2014-05-20 23:38:20

标签: sql oracle oracle11g null pivot

post让我开始了。

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   

2 个答案:

答案 0 :(得分: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 :(得分: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