非常感谢你的帮助。 我正在使用一个包含两列的表:EmployeeID和Color。我使用以下(非常简单的)代码拉这两列:
Select
EmployeeID,
Color
From
dbo.EmployeeID E
join dbo.Color C on C.EmployeeID = E.EmployeeID
结果以下列格式返回。有几百行具有不同的employeeID,颜色组合。:
EmployeeID Color
123 Blue
123 Green
123 Yellow
234 Blue
234 Green
我想转动数据,以便结果如下所示:
EmployeeID Color1 Color2 Color3
123 Blue Green Yellow
234 Blue Green
我过去使用过枢轴功能来聚合数据,但这次我无法弄清楚。我认为不需要聚合功能会让我失望。如果我使用MIN或MAX作为PIVOT的功能,我不知道如何获得每个EmployeeID的所有颜色。
感谢任何帮助,我经常遇到同样的情况,并且很想知道如何导航。
谢谢!
答案 0 :(得分:4)
如果您知道自己想要PIVOT
的列数,则可以与ROW_NUMBER()
DECLARE @t TABLE (EmployeeID INT, Color VARCHAR(10))
INSERT @t
VALUES(123,'Blue'),
(123,'Green'),
(123,'Yellow'),
(234,'Blue'),
(234,'Green'),
(456,'Yellow'),
(456,'Blue')
;WITH c AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY EmployeeId ORDER BY Color) rn
FROM @t
)
SELECT EmployeeId, [1], [2], [3]
FROM c
PIVOT(
MAX(Color) FOR rn IN ([1], [2], [3])
) pvt
答案 1 :(得分:0)
with
t as ( select E.EmployeeID ,
Color
from E
join C on C.EmployeeID = E.EmployeeID
)
select EmployeeID ,
Blue ,
Green ,
Yellow
from t pivot ( min(Color) for Color in ( Blue, Green, Yellow ) ) pvt
答案 2 :(得分:0)
您可以使用以下查询获取预期结果
select [EmployeeID], [Blue] as column1,[Green] as column2, [Yellow] as column2 from
(
Select
e.EmployeeID,
Color
From
dbo.EmployeeID E
join dbo.Color C on C.EmployeeID = E.EmployeeID
) a
pivot
(
max(color)
for color in ([Blue],[Green] , [Yellow])
) as pv;