选择SQL Row值作为pivot之类的列

时间:2017-10-27 10:28:49

标签: sql sql-server pivot

我有一张桌子

 ID   TYPE A   TYPE B   TYPE C
1001   3         0        9
1002   8         5        0
1003   0         1        7

我需要获得的输出应该是这样的

{{1}}

我该怎么做?

3 个答案:

答案 0 :(得分:3)

如果您不想SQLDynamic,可以尝试Pivot以下查询:

SELECT id,
       ISNULL(SUM(CASE(type)
                      WHEN 'A'
                      THEN VALUE
                  END), 0) [TYPE A],
       isnull(SUM(CASE(type)
                      WHEN 'B'
                      THEN VALUE
                  END), 0) [TYPE B],
       isnull(SUM(CASE(type)
                      WHEN 'C'
                      THEN VALUE
                  END), 0) [TYPE C]
FROM <table_name>
GROUP BY id;

结果:

ID      TYPE A  TYPE B  TYPE C 
1001    3       0       9
1002    8       5       0
1003    0       1       7

答案 1 :(得分:1)

你可以尝试:

   Select *

    From(
        'Insert Your Original Query Here or Table Name'    ) P

    Pivot   
        (Sum(Value)
            For TYPE in ([Type A],[Type B],[Type C]) As pvt
    Order By
        ID

答案 2 :(得分:0)

试试这个动态的sql

DECLARE @SQL nvarchar(max),
        @Columns nvarchar(max),@ColumnsType nvarchar(max)


SELECT @Columns=STUFF((SELECT DISTINCT ', '+QUOTENAME([TYPE])  FROM #table FOR XML PATH ('')),1,2,'')

SELECT @ColumnsType=STUFF((SELECT DISTINCT ', '+'ISNULL ('+QUOTENAME([TYPE])+','+'''0'''+') AS '+ 'Type'+[TYPE] FROM #table FOR XML PATH ('')),1,2,'')


SET @SQL='
SELECT ID,'+@ColumnsType+' From
(
SELECT * FROM #table
)
AS Src
    PIVOT
    (
    SUM(VALUE) FOR [TYPE] IN ('+@Columns+')
    )as Pvt
'
Print @SQL
EXEC (@SQL)

结果

ID      TypeA   TypeB   TypeC
-------------------------------
1001    3        0       9
1002    8        5       0
1003    0        1       7