需要在SQL中选择具有不同条件的相同字段的总和

时间:2015-03-21 07:00:01

标签: mysql sql

我有两个表用于选择具有不同条件的相同字段的总和现在尝试查询如下但是结果在两个字段中显示相同

SELECT  sum( s.message_count) as total,(case when s.dlr_status = 'DELIVRD' then sum( s.message_count) end ) as delivered  
FROM `sent` s join `track` t on t.track_id = s.track_id  group by t.sent_type

任何帮助都会很明显  谢谢

1 个答案:

答案 0 :(得分:0)

sum移到case..when投影之外,为了完整起见,请在'其他'中返回零。您还需要选择中的sent_type列才能按其进行分组。

SELECT  
    t.sent_type,
    sum(s.message_count) as total,
    sum(case when s.dlr_status = 'DELIVRD' then s.message_count else 0 end) as delivered  
FROM `sent` s join `track` t on t.track_id = s.track_id  
group by t.sent_type;