答案 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