[英]Use aggregation only on rows where count(ID) is greater than one
嗨,我有下表
Cash_table
ID Cash Rates
1 50 3
2 100 4
3 70 10
3 60 10
4 13 7
5 20 8
5 10 10
6 10 5
因此,我想要的是累積所有具有Count(id)> 1的條目,如下所示:
ID New_Cash New_Rates
1 50 3
2 100 4
3 (70+60)/(10+10) 10+10
4 13 7
5 (20+10)/(8+10) 8+10
6 10 5
所以我只想更改Count(id)> 1的行,其余的保持原樣。
對於count(id)> 1的行,我想對比率求和,取現金總和除以比率總和。 僅憑費率就不成問題,因為我可以對它們進行匯總並按ID分組並獲得所需的結果。
問題在於現金欄:
我正在嘗試使用一個case語句來執行此操作,但是它不起作用:
select id, sum(rates) as new_rates, case
when count(id)>1 then sum(cash)/nullif(sum(rates),0))
else cash
end as new_cash
from Cash_table
group by id
您只需group by id
並進行匯總:
select
id,
sum(cash) / (case count(*) when 1 then 1 else sum(rates) end) as new_cash,
sum(rates) as new_rates
from Cash_table
group by id
order by id
參見演示 。
您可以通過sum()
函數匯總rate
和cash
列,並按ID進行分組
select
id,
sum(cash)/decode( sum( nvl(rates,0) ), 0 ,1, sum( nvl(rates,0) )) as new_cash,
sum(rates) as new_rates
from cash_table
group by id
nullif()
函數,請改用nvl()
decode()
函數)以防止被零除的可能性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.