Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SUM() data in a column based on another 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 iam new to sql,i am little confuse to use SUM() based on above condition.

like image 490
Chow.Net Avatar asked Oct 25 '12 02:10

Chow.Net


3 Answers

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?

like image 138
John Woo Avatar answered Nov 19 '22 06:11

John Woo


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
like image 33
Niladri Biswas Avatar answered Nov 19 '22 05:11

Niladri Biswas


select min("Project ID")as 'Project ID',"Employee ID"
   , SUM("Total Days") as 'Total Days'
from table1
group by "Employee ID"
like image 1
Fathah Rehman P Avatar answered Nov 19 '22 06:11

Fathah Rehman P