将单个列转换为行并对microsoft server 2008进行分组

时间:2015-05-28 05:28:10

标签: sql sql-server-2008 tsql

我有一个以下格式的表格;

ID | Factors | Value  
---------------------
1  |    A    |  4542
1  |    B    |  454
1  |    C    |  43

我需要转置因子列并对id列进行分组,以便得到以下结果;

ID|  A   |  B  | C  |
1   | 4542 | 454 | 43 |

我已经研究了枢轴功能,但从我读过的内存非常密集,我处理的是1000和ID和值。

我尝试使用我想要的列创建一个表,但不知道如何将正确的数据插入其中。

1 个答案:

答案 0 :(得分:3)

实现这一目标的两种常见方法是Pivot:

SELECT ID AS NMI, [A], [B], [C]
FROM 
MyTable
PIVOT
(
    SUM(Value)
    FOR Factors in ([A], [B], [C])
) pvt;

或使用手动CASE ... WHEN投影与分组聚合:

SELECT 
    ID AS NMI, 
    SUM(CASE WHEN Factors = 'A' THEN Value END) AS [A], 
    SUM(CASE WHEN Factors = 'B' THEN Value END) AS [B],
    SUM(CASE WHEN Factors = 'C' THEN Value END) AS [C]
FROM MyTable
GROUP BY ID;

Fiddle of both here