表格数据的非线性,三向和

时间:2012-10-12 14:44:37

标签: mysql sql

我的table

user_name     id      status          calls
===========================================
apple        21       BadAd             2
apple        21       Lead              5
apple        21       DNC               6
apple        21       pajs              2
orange       34       Lead              9
orange       34       disks             3
orange       34       BadAd             8
orange       34       pajs              5

我的尝试

 SELECT sum(calls) FROM (SELECT y.calls, y.user_name, y.status FROM stats
 INNER JOIN
 (select user_name, status, sum(calls) as calls
 from stats WHERE status = ('BadAD', 'Lead', 'DNC')
 group by user_name, status) y
 ON y.user_name = stats.user_name
 GROUP BY y.status) w WHERE w.user_name = y.username

我的问题:我正在尝试添加仅包含特定calls字段值(status)并且具有相同user_name的行的WHERE status = ('BadAD', 'Lead', 'DNC')字段中的值。所以它看起来像这样。

user_name     id      status          calls
===========================================
apple        21       BadAd             13           (BadAd 2 + Lead 5 + DNC 6)
orange       34       Lead              17           (etc..)

1 个答案:

答案 0 :(得分:2)

select user_name, id, min(status), sum (calls)
from yourtable
where status in  ('BadAD', 'Lead', 'DNC')
group by user_name, id
相关问题