2016-12-20 131 views
2

比方說,比如我有如下記錄的表...結合了相同的ID記錄,但不同的屬性到一個記錄

ID | Attribute 
1  BLUE 
1  GREEN 
1  RED 
2  YELLOW 
2  GREEN 
3  GREEN 

我想將它與所有的屬性凝結成1分的紀錄。

ID | Attribute1 | Attribute2 | Attribute3 
1  BLUE   GREEN   RED 
2  YELLOW  GREEN 
3  GREEN 

我標題下PIVOT的路徑,但不知道如何清楚地插入屬性分爲單獨的列考慮它們共享相同的ID /密鑰。我正在使用SSMS。

+1

哪'DBMS'您正在使用? –

+0

每個「ID」最多可以有3個「屬性」,或者它是未知的? –

+0

SQL Server Management Studio – OhioMike1987

回答

2

試試這個

;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) 
+0

這工作完美!我只是拋出NULL而不是''。感謝幫助!在使用CTE時需要磨合一些。 – OhioMike1987

2

如果你不需要去動態的,有條件的聚集可以幫助

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 (
     Select * 
       ,RN = Row_Number() over (Partition By ID Order By Attribute) 
     From YourTable 
    ) 
Group By ID 
0

這應該是非常簡單易用

select * from(
     select 
      ID 
      ,Attribute 
      ,row_number() over(partition by ID order by Attribute) as AttributeNumber 
     from [YourTable] 
     group by ID 
       ,Attribute 
      )t1 
PIVOT 
(
MAX(Attribute) 
FOR AttributeNumber in ([1],[2],[3])-- add more as needed 
)piv 
相關問題