SUM () on a column based on other column data

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 new to sql, I'm a little confused to use SUM () based on the above condition.

+2


source to share


3 answers


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

      

+2


source


This example below creates two columns: EmployeeID

, totalDays

.

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

      



follow-up question: why the desired result projectId

there 1 and 2

?

+2


source


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

      

+1


source







All Articles