将多行分组到一行

时间:2015-02-06 09:22:52

标签: sql sql-server sql-server-2008 tsql

我有一组数据,其中包含一行的多个属性。

例如,每位员工都可以参加多项活动,每项活动都有一个分数。当我从数据库查询时,EmployeeID将在所有行中重复,如下所示:

enter image description here

我想要的是对数据进行group by排序,使得每一行是一个Employee记录及其活动和分数如下:

enter image description here

我试图像这样做一个小组:

select Employee.EmployeeID, Games.Activity, Games.Score from Employee left join Games on Employee.GameID = Games.GameID
group by Employee.EmployeeID;

然而,这不起作用。如果不在select子句中使用聚合函数,我该怎么办?

1 个答案:

答案 0 :(得分:0)

1.User窗口函数Row_number(),分区为EmployeeID

2.然后只需使用Case when then获取第一行作为EmployeeID

select case when NewTab.RN =1 then NewTab.EmployeeID else null,NewTab.Activity, NewTab.Score
from (
select ROW_NUMBER() OVER(partition BY Employee.EmployeeID ORDER BY Employee.EmployeeID)RN,* from (
select Employee.EmployeeID, Games.Activity, Games.Score from Employee 
left join Games on Employee.GameID = Games.GameID
group by Employee.EmployeeID)D
)NewTab