試試這個
;WITH cte
AS (SELECT *,Row_number()OVER(partition BY [ID] ORDER BY [Attribute]) rn
FROM Yourtable)
SELECT [ID],
Max(CASE WHEN rn = 1 THEN [Attribute] ELSE '' END) AS [Attribute1],
Max(CASE WHEN rn = 2 THEN [Attribute] ELSE '' END) AS [Attribute2],
Max(CASE WHEN rn = 3 THEN [Attribute] ELSE '' END) AS [Attribute3]
FROM cte
GROUP BY [ID]
如果你想與數目不詳的屬性,然後
工作
DECLARE @int INT = 1,
@cnt INT,
@sql VARCHAR(max)
SELECT TOP 1 @cnt = Count(1)OVER(partition BY [ID])
FROM Yourtable
ORDER BY Count(1)OVER(partition BY [ID]) DESC
SET @sql = ';WITH cte
AS (SELECT *,Row_number()OVER(partition BY [ID] ORDER BY [Attribute]) rn
FROM Yourtable)
SELECT [ID],'
WHILE @int <= @cnt
BEGIN
SET @sql += 'Max(CASE WHEN rn = ' + Cast(@int AS VARCHAR(20)) + ' THEN [Attribute] ELSE '''' END) AS [Attribute' + Cast(@int AS VARCHAR(20)) + '],'
SET @int +=1
END
SET @sql = LEFT(@sql, Len(@sql) - 1)
SET @sql += 'FROM cte GROUP BY [ID]'
exec (@sql)
哪'DBMS'您正在使用? –
每個「ID」最多可以有3個「屬性」,或者它是未知的? –
SQL Server Management Studio – OhioMike1987