SQL PIVOT生成所需的输出

时间:2016-09-19 08:53:11

标签: sql sql-server

请参阅以下数据:

enter image description here

我正在寻找一个生成以下输出的查询:

enter image description here

我正在尝试使用PIVOT'但尚未达到预期的效果。

3 个答案:

答案 0 :(得分:3)

这应该有效:

SELECT ReviewType, DER, LEI, NOR, [NOT], LIN
FROM Src
PIVOT (SUM(Total) FOR OwningAgency IN (DER, LEI, NOR, [NOT], LIN)) P

答案 1 :(得分:1)

简单的旋转:

SELECT *
FROM YourTable
PIVOT (
    MAX(Total) FOR OwningAgency IN ([DER],[LEI],[NOR],[NOT],[LIN])
) pvt

另一种方式:

SELECT  ReviewType,
        CASE WHEN OwningAgency = 'DER' THEN MAX(Total) END [DER],
        CASE WHEN OwningAgency = 'LEI' THEN MAX(Total) END [LEI],
        CASE WHEN OwningAgency = 'NOR' THEN MAX(Total) END [NOR],
        CASE WHEN OwningAgency = 'NOT' THEN MAX(Total) END [NOT],
        CASE WHEN OwningAgency = 'LIN' THEN MAX(Total) END [LIN]
FROM YourTable
GROUP BY ReviewType,OwningAgency

答案 2 :(得分:1)

使用动态列集合来选择PIVOT数据,因为它会为您提供表格中添加的任何新列值,假设2-3天后新OwningAgency 对XYZ说添加到您的表,即使它在PIVOT中显示您的新列结果:

CREATE TABLE tblOwningAgency
 (
   OwningAgency  VARCHAR(50),
   ReviewType CHAR(1),
   Total INT
 )  

 INSERT INTO tblOwningAgency VALUES('DER','E',584)
 ,('LEI','S',84)
 ,('NOR','S',28148)
 ,('LIN','S',1261)
 ,('DER','T',6310)
 ,('NOR','T',5527)
 ,('NOT','T',35705)
 ,('LIN','E',606)
 ,('NOT','S',22978)
 ,('LEI','T',4283)
 ,('LIN','T',687)
 ,('LEI','E',431)
 ,('NOR','E',161)
 ,('NOT','E',842)
 ,('DER','S',1937)
 ,('XYZ','S',1937)

DECLARE @OwningAgency AS NVARCHAR(MAX),@Query  AS NVARCHAR(MAX);

SET @OwningAgency = STUFF((SELECT distinct ',' + QUOTENAME(OwningAgency) 
            FROM tblOwningAgency c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @Query = 
'SELECT ReviewType, ' + @OwningAgency + ' from 
(
    SELECT *
    FROM tblOwningAgency
) x
pivot 
(
    SUM(Total)
    FOR OwningAgency in (' + @OwningAgency + ')
) p '

EXECUTE(@query)

@OwningAgency:它会为您提供要应用SUM的列列表