简体   繁体   English

仅当存在具有特殊条件的另一行时才求和字段

[英]sum field only if another row with a special condition exists

I have a table with the following entries: 我有一个包含以下条目的表:

id customer amount kind
1  123      15     g
2  123      30     op
3  234      20     g
4  345      25     g
5  456      12     g
6  456      15     op

What I want to do is to sum all amounts with the kind "g". 我想做的是将所有金额加为“ g”。

Now I want to add a condition: 现在我要添加一个条件:

"Only sum the amount to the sum if there is another entry of the customer with the kind 'op'" “只有当客户的另一个输入为'op'时,才将金额加起来。”

Means my result should be 27 in this case and not 72. 意味着在这种情况下,我的结果应该是27,而不是72。

What's a good way to add this condition? 添加此条件的好方法是什么?

Thanks! 谢谢!

To get the sum for each customer do 为了获得每个客户的总和

select customer, sum(case when kind = 'g' then amount else 0 end) as c_sum
from your_table
group by customer
having sum(kind = 'op') > 0

to get the total sum do 得到总和

select sum(c_sum)
from 
(
    select customer, sum(case when kind = 'g' then amount else 0 end) as c_sum
    from your_table
    group by customer
    having sum(kind = 'op') > 0
) tmp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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