简体   繁体   中英

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".

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'"

Means my result should be 27 in this case and not 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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