2017-09-22 54 views
0

本来我有一个SQL Server表如下图所示:SQL服务器:转换行到列的无支点和分组

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 

能这样做吗?我不认为这个关键点会有帮助,因为我对于多个数值组合有相同的结果。

+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; 
+0

非常感谢。这可以动态完成吗?像标题颜色一样,尺寸,形状可以因颜色,宽度,高度等其他结果而异。在这种情况下如何处理? –

+0

@GopalB。 。 。我建议你Google“SQL Server动态数据透视表”。 –