sql表行 - 列转换

时间:2013-08-28 09:41:16

标签: sql sql-server pivot

我有以下表格:

enter image description here

如何将上表转换为以下结构?我尝试使用数据透视表但无法使其工作。

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要查找SQL PIVOT

检查this fiddle

代码:

SELECT    * 
FROM 
(
    SELECT    Prodname, 
              pcode, 
              Biiledamt
    FROM      Product
) p
PIVOT 
(
    SUM    (Biiledamt)
    FOR    Prodname IN ([Prod1],[Prod2],[Prod3],[Prod4])
)   AS pvt

如果您事先不知道列,则可以check this fiddle动态生成要使用的列。

代码是:

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

SET @cols = STUFF((SELECT distinct ',[' + Prodname +']'
            FROM Product c
            FOR XML PATH(''), TYPE
            ).value('.', 'VARCHAR(MAX)') 
        ,1,1,'')


SET @query = 
'    SELECT    * 
    FROM 
    (
        SELECT    Prodname, 
                  pcode, 
                  Biiledamt
        FROM      Product
    ) p
    PIVOT 
    (
        SUM    (Biiledamt)
        FOR    Prodname IN (' + @cols + ')
    )   AS pvt
'


EXEC(@query)