如果基于另一列中的值,则求和

时间:2013-01-31 17:28:05

标签: sql sum

在下面的代码中,我希望AdminDuration和BreakDuration根据UserID的值进行求和。目前我无法弄明白,并且它使用ReasonCode 7对所有持续时间的值求和。结果每个UserId都是相同的持续时间(不是我想要的!)。

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

1 个答案:

答案 0 :(得分:8)

如果我理解正确,那应该是:

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