0

我的 Sql 表类似如下

Code  Value  ID
A     100    1
A     200    2
A     300    3
B     200    1
B     500    2
B     600    3
C     800    1 
C     700    2
C     200    3

如何在 sql server 2008 中编写查询以获取以下格式的值。

ID A    B    C
1  100  200  800
2  200  500  700
3  300  600  200 
4

3 回答 3

3

您可以SUM为此使用函数:

SELECT ID,
        SUM(CASE Code when 'A' then Value else 0 end)as A,
        SUM(CASE Code when 'B' then Value else 0 end)as B,
        SUM(CASE Code when 'C' then Value else 0 end)as C
FROM myTable
GROUP BY ID;

看到这个 SQLFiddle

于 2012-09-10T10:41:44.683 回答
2

使用枢轴

select ID,[A],[B],[C]
from your_table T
PIVOT (MAX(Value) FOR Code in ([A],[B],[C]) )P


如果代码不固定的数字,您可以使用动态枢轴

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Code) 
                    from your_table
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ID,  ' + @cols + '  
                from your_table
            pivot 
            (
                MAX([Value])
                for Code in (' + @cols + ')
            ) p '
print(@query)
execute(@query)
于 2012-09-10T10:35:00.463 回答
1

答案是枢轴

DECLARE @t TABLE (Code varchar(10), Value int, Id int)

INSERT INTO @t VALUES
                    ('A',100,1),
                    ('A',200,2),
                    ('A',300,3),
                    ('B',200,1),
                    ('B',500,2),
                    ('B',600,3),
                    ('C',800,1),
                    ('C',700,2),
                    ('C',200,3);

SELECT ID,[A],[B],[C]
FROM @t
PIVOT (SUM(Value) FOR Code IN ([A],[B],[C]))P

结果

ID  A   B   C
1   100 200 800
2   200 500 700
3   300 600 200
于 2012-09-10T10:52:38.260 回答