转置/动态PIVOT

时间:2017-04-21 08:57:07

标签: sql sql-server xml for-loop pivot

enter image description here

进入以下内容:

enter image description here

信用额度为6.空白点可以为空。我想创建名为Credit1,Credit2,..,Credit6的新列。我可以在这种情况下使用PIVOT吗?或者转换表的任何其他简单方法?

1 个答案:

答案 0 :(得分:1)

您可以使用动态SQL版本:

CREATE TABLE  #SampleData 
(
   Name varchar(50),
   Credits int
)

INSERT INTO #SampleData
VALUES ('John', 10),('John', 20),
('Bath', 90), ('Bath', 60), ('Bath', 70),('Bath', 80),('Bath', 50),
('Richard', 75)

DECLARE @ColPivot nvarchar(max)
;WITH temp AS
(
   SELECT * , 'Credit' + CAST(row_number() OVER(PARTITION BY sd.Name ORDER BY (SELECT 1)) AS varchar(5)) AS CreditGroup
   FROM #SampleData sd
)
SELECT @ColPivot = STUFF(
                    (SELECT DISTINCT ',' + t.CreditGroup FROM temp t FOR XML PATH (''))
                   ,1,1,'')

DECLARE @query nvarchar(max) = 
      N';WITH temp AS
        (
            SELECT * , ''Credit'' + CAST(row_number() OVER(PARTITION BY sd.Name ORDER BY (SELECT 1)) AS varchar(5)) AS CreditGroup
            FROM #SampleData sd
        )
         Select [Name],  ' + @ColPivot + 
        ' FROM 
         (
            SELECT [Name], Credits, CreditGroup FROM temp 
         ) src
         PIVOT
         (
            MAX(Credits) FOR CreditGroup IN ('+ @ColPivot+ ')
         )pvt
        '
PRINT @query

EXEC (@query)

DROP TABLE #SampleData

演示链接:Rextester