Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum if based on value in another column

Tags:

sql

sum

In the below code, I want the AdminDuration and BreakDuration to sum based on what the value of UserID is. At the moment I can't figure it out, and it sums the values of all Durations with ReasonCode 7. As a result every UserId has the same Duration (not what I want!).

Select SkillTargetID AS UserID,
(SELECT sum(Duration) 
   from [t_Agent_Event_Detail] 
   where ReasonCode = 7
   and DateTime > convert(DATETIME, '2013-01-31 08:00', 21)) as AdminDuration,
(SELECT sum(Duration) 
   from [t_Agent_Event_Detail] 
   where ReasonCode = 6
   and DateTime > convert(DATETIME, '2013-01-31 08:00', 21) 
   and SkillTargetID = [t_Agent_Event_Detail].SkillTargetID) as BreakDuration 
from [t_Agent_Event_Detail]
GROUP BY SkillTargetID
like image 470
Larnu Avatar asked Jan 31 '13 17:01

Larnu


1 Answers

If I understand you correctly, it should be:

SELECT SkillTargetID AS UserID,
       sum(CASE WHEN ReasonCode = 7 THEN Duration ELSE 0 END) as AdminDuration,
       sum(CASE WHEN ReasonCode = 6 THEN Duration ELSE 0 END) as BreakDuration
FROM [t_Agent_Event_Detail]
WHERE DateTime > convert(DATETIME, '2013-01-31 08:00', 21)
GROUP BY SkillTargetID
like image 78
Anton Kovalenko Avatar answered Nov 15 '22 04:11

Anton Kovalenko