[英]Calculate column based on previous value of the same calculated column in MySQL
[英]How can we calculate the value based on the ratio that calculated from the number of previous column by SQL?
让我解释一下:我的数据
Cus_name Group Cus_received Bonus
X A 1000 16,5
Y A 2000 46,5
Z A 3000 76,5
Bonus = (Cus_received - 450$) * 0,03 -- 450, 0,03 在我们的公式中是常数 --
在这种情况下,Bonus 列计算错误。 如果A组只有1个客户,结果是正确的。 但是因为A组有3个客户,结果应该是这样的
X:Y:Z = 1000:2000:3000= 1:2:3
Sum= 1000+2000+3000=6000.
Sum(bonus)= (6000 - 450) * 0,03 = 166,5
then Bonus(X) = 166,5 * 1 / (1+2+3) = 27,5
Bonus(Y) = 166,5 * 2 / (1+2+3) = 55
Bonus (Z)= 166,5 * 3 / (1+2+3) = 83,25
就像我描述的如果A组只有1个客户,结果是正确的。 但是如果同一组中n个客户>1,则bonus列需要根据sum(cus_received)计算,然后除以比例。 请帮我解决如何通过SQL构建这个过程? 谢谢!
您需要使用分析函数SUM
计算所有行的总体结果,将您的公式应用于该总和,并通过将当前值 ov A
除以该总和来计算比率。 因为您没有提供任何“计算佣金的公式”,所以我使用了固定百分比。
with a as (
select 1 as n, 1000 as A from dual union all
select 2 as n, 2000 as A from dual union all
select 3 as n, 3000 as A from dual
)
select
n,
a,
( a / sum(a) over() )
* ( 0.15 * sum(a) over() /*15% comm rate*/) as b
from a
这回答了问题的原始版本。
如果我假设佣金率为 0.33333333%——这将是 6000 美元的 20 美元佣金,那么您可以在每一行中计算它:
select t.*, a * (20.0 / 6000) as b
from t;
如果您想将 20 美元分散在三行中,则使用窗口函数来计算比率:
select t.*,
(20 * a / sum(a) over ()) as b
from t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.