简体   繁体   中英

Sum if based on value in another column

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 Duration s 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM