Reputation: 593
I have a sql table
Project ID Employee ID Total Days
1 100 1
1 100 1
1 100 2
1 100 6
1 200 8
1 200 2
Now i need this table to look like
Project ID Employee ID Total Days
1 100 10
1 200 10
As iam new to sql,i am little confuse to use SUM() based on above condition.
Upvotes: 7
Views: 55203
Reputation: 8761
select min("Project ID")as 'Project ID',"Employee ID"
, SUM("Total Days") as 'Total Days'
from table1
group by "Employee ID"
Upvotes: 1
Reputation: 4171
Here are two approaches
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
Result
ProjectId EmployeeId TotalDays
1 100 10
1 200 10
Upvotes: 6
Reputation: 263893
This query below produces two columns: EmployeeID
, totalDays
.
SELECT EmployeeID, SUM(totalDays) totalDays
FROM tableName
GROUP BY EmployeeID
follow-up question: why is in your desired result the projectId
is 1 and 2
?
Upvotes: 6