简体   繁体   中英

Group by and divide

I have the table below on sql of accounting accounts (A is a cost account and B a headcount ), and cc as cost center. So what i want to do is divide the amount of account A over account B for each cc

Account cc Amount
A x 1
A y 2
B z 4
B y 1
A z 1
B x 2

So the result would be:

Account cc Amount
A x 1 /2
A y 2
B z 0
B y 0
A z 1 /4
B x 0

I was thinking about a group by but Im a very beginner in sql and don't know how to use it thanks in advance for your help!

For the results you specify, you can use window functions:

select t.*,
       (case when account = 'A'
             then amount * 1.0 / sum(case when account = 'B' then amount end) over (partition by cc)
             else 0
        end) as ratio
from t;

I would just use a regular group by with some cases:

with cc_amts as (
select cc,
    sum(case when account = 'A' then amount else 0 end) amt_a,
    sum(case when account = 'B' then amount else 0 end) amt_b
from t
group by cc)
select cc, amt_a / amt_b
from cc_amts;

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