簡體   English   中英

僅當存在具有特殊條件的另一行時才求和字段

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

我有一個包含以下條目的表:

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

我想做的是將所有金額加為“ g”。

現在我要添加一個條件:

“只有當客戶的另一個輸入為'op'時,才將金額加起來。”

意味着在這種情況下,我的結果應該是27,而不是72。

添加此條件的好方法是什么?

謝謝!

為了獲得每個客戶的總和

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

得到總和

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