2016-12-20 99 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 
相关问题