5

我有一个 sql 表

Project ID       Employee ID          Total Days

1                   100                   1
1                  100                   1
1                  100                   2
1                   100                   6
1                   200                   8
1                   200                   2

现在我需要这张桌子看起来像

Project ID       Employee ID          Total Days

1                   100                   10
1                   200                   10

作为 sql 新手,我对根据上述条件使用 SUM() 有点困惑。

4

3 回答 3

5

下面的这个查询产生两列:EmployeeID, totalDays

SELECT  EmployeeID, SUM(totalDays) totalDays
FROM    tableName
GROUP BY EmployeeID

后续问题:为什么在您想要的结果中projectId1 and 2

于 2012-10-25T02:42:05.640 回答
2

这里有两种方法

Declare @t Table(ProjectId Int, EmployeeId Int,TotalDays Int)
Insert Into @t Values(1,100,1),(1,100,1),(1,100,2),(1,100,6),(1,200,8),(1,200,2)

方法1:

Select ProjectId,EmployeeId,TotalDays = Sum(TotalDays)
From @t 
Group By ProjectId,EmployeeId

方法2:

;With Cte As(
Select 
    ProjectId
    ,EmployeeId
    ,TotalDays = Sum(TotalDays) Over(Partition By EmployeeId)
    ,Rn = Row_Number() Over(Partition By EmployeeId Order By EmployeeId)
From @t )
Select ProjectId,EmployeeId,TotalDays
From Cte Where Rn = 1

结果

ProjectId   EmployeeId  TotalDays
1            100        10
1            200        10
于 2012-10-25T03:29:08.403 回答
1
select min("Project ID")as 'Project ID',"Employee ID"
   , SUM("Total Days") as 'Total Days'
from table1
group by "Employee ID"
于 2012-10-25T02:49:45.883 回答