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

How to use Pivot on two columns in sql

我的 table 中有如下数据。 Flag 是 bit,label 是 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 获取标签,但是当我为标志提供第二个聚合函数时,它给出了错误(“,”附近的语法不正确)。有什么方法可以使用 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

我发现使用 pivot 运算符执行此操作有点棘手,而使用条件聚合更容易:

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

是的,但它们需要单独旋转。它需要一些花哨的步法,但它看起来应该更像:

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