基于另一列数据的列中的SUM()数据

时间:2012-10-25 02:39:08

标签: sql sql-server-2008

我有一个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()。

3 个答案:

答案 0 :(得分:2)

以下此查询会生成两列:EmployeeIDtotalDays

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

后续问题:为什么projectId 1 and 2为{{1}}?

答案 1 :(得分: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)

<强> Approach1:

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

<强> Approach2:

;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

答案 2 :(得分:1)

select min("Project ID")as 'Project ID',"Employee ID"
   , SUM("Total Days") as 'Total Days'
from table1
group by "Employee ID"