简体   繁体   English

分组和划分

[英]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.我有下表 sql 的会计科目(A 是成本科目,B 是人数),cc 作为成本中心。 So what i want to do is divide the amount of account A over account B for each cc所以我想要做的是将账户 A 的金额除以每个 cc 的账户 B

Account帐户 cc抄送 Amount数量
A一个 x X 1 1
A一个 y是的 2 2
B z z 4 4
B y是的 1 1
A一个 z z 1 1
B x X 2 2

So the result would be:所以结果是:

Account帐户 cc抄送 Amount数量
A一个 x X 1 /2 1 /2
A一个 y是的 2 2
B z z 0 0
B y是的 0 0
A一个 z z 1 /4 1 /4
B x X 0 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!我正在考虑一个小组,但我是 sql 的初学者,不知道如何使用它提前感谢您的帮助!

For the results you specify, you can use window functions:对于您指定的结果,您可以使用 window 函数:

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;

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

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