【问题标题】:Sum if based on value in another column如果基于另一列中的值求和
【发布时间】:2013-01-31 17:28:04
【问题描述】:

在下面的代码中,我希望 AdminDurationBreakDuration 根据 UserID 的值求和。目前我无法弄清楚,它将所有Durations 的值与ReasonCode 7 相加。结果每个UserId 都有相同的Duration(不是我想要的!)。

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

【问题讨论】:

    标签: sql sum


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多