[英]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 ![]() |
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!我正在考虑一个小组,但我是 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.