SQL Server:将行转换为没有透视和分组的列

时间:2017-09-22 20:18:45

标签: sql sql-server

最初我有一个SQL Server表,如下所示:

Result  Type    Type Order  Type Value
--------------------------------------
KM1    Color    1             Blue
KM1    Shape    2             Square
KM1    Size     3             10
KM3    Color    1             Blue
KM3    Shape    2             Square
KM3    Size     3             10
KM2    Color    1             Red
KM2    Shape    2             Round
KM2    Size     3             20
KM2    Color    1             Blue
KM2    Shape    2             Square
KM2    Size     3             10
KM2    Color    1             Blue
KM2    Shape    2             Round
KM2    Size     3             10

我的预期结果应该是

Color   Shape   Size    Result
-------------------------------------
Blue    Square   10     KM1, KM3, KM2
Red     Round    20     KM2
Blue    Round    10     KM2

可以这样做吗?我不认为枢轴会有所帮助,因为我对多个值的组合有相同的结果。

1 个答案:

答案 0 :(得分:2)

这是两个级别的聚合。首先是描述每个结果。第二是将钥匙放在一起。所以:

with t as (
      select result,
             max(case when type = 'Color' then value end) as color,
             max(case when type = 'Size' then value end) as size,
             max(case when type = 'Shape' then value end) as shape
      from t
      group by result
     )
select color, size, shape,
       stuff( (select ',' + t2.result
               from t t2
               where t2.color = t.color and t2.size = t.size and t2.shape = t.shape
               for xml path ('')
              ), 1, 1, '') as keys
from (select distinct color, size, shape
      from t
     ) t;