如何在sql中的两列上使用Pivot

时间:2015-08-14 22:34:36

标签: sql pivot unpivot

我的表格中有如下数据。标志位是bit,标签是varchar。

parentid code label  flag
1       abc   hello   false
1       xyz   bye     false
1       qrt   hi      true

我需要将记录提取为

parentid  label_abc flag_abc  label_xyz flag_xyz  label_qrt flag_qrt

我现在只能使用Pivot获取标签,但是当我为flag提供第二个聚合函数时,它会给出错误(语法不正确,','。)。有没有办法使用Pivot获取两列。

我做了类似的事情:

SELECT distinct
       parentid     
       , [abc] as label_abc 
       , [xyz] as label_xyz 
       , [qrt] as label_qrt
FROM (
Select 
    parentid,   
    label,code  
FROM items 
   ) a
Pivot ( 
Max(label), max (flag)
FOR code in ([abc], [xyz], [qrt]
   ) as Pvt

2 个答案:

答案 0 :(得分:1)

I find it a bit tricky to do this using the pivot operator, and a lot easier to use conditional aggregation instead:

select 
    parentid, 
    max(case when code = 'abc' then label end) as label_abc, 
    max(case when code = 'abc' then flag  end) as flag_abc, 
    max(case when code = 'xyz' then label end) as label_xyz, 
    max(case when code = 'xyz' then flag  end) as flag_xyz, 
    max(case when code = 'qrt' then label end) as label_qrt, 
    max(case when code = 'qrt' then flag  end) as flag_qrt
from ( 
    select parentid, code, label, cast(flag as int) flag 
    from items 
) src
group by parentid;

Sample SQL Fiddle

答案 1 :(得分:0)

yes, but they need to be pivoted separately. it takes a little bit of fancy footwork, but it should look more like:

select distinct parentid
, [abc1] as label_abc 
, [xyz1] as label_xyz 
, [qrt1] as label_qrt
, [abc2] as flag_abc 
, [xyz2] as flag_xyz 
, [qrt2] as flag_qrt
from (
    select parentid
    , label
    , label + '1' as code1
    , label + '2' as code2
    from items 
) as a
pivot (
    max(label) for code1 in ([abc1], [xyz1], [qrt1])
) as pvt1
pivot (
    max(flag) for code2 in ([abc2], [xyz2], [qrt2])
) as pvt2