[英]Subtract current row from previous row, keeping previous row value as constant — SQL
Table product has average revenue by product表产品按产品划分的平均收入
product![]() |
avg_rev ![]() |
---|---|
A![]() |
500 ![]() |
B![]() |
400 ![]() |
C ![]() |
250 ![]() |
D ![]() |
100 ![]() |
Table product_diff, is where I need to calculate, diff_a as another column where formula aa, ab, ac, ad carries over.表 product_diff,是我需要计算的地方,diff_a 作为公式 aa、ab、ac、ad 继承的另一列。
product![]() |
avg_rev ![]() |
diff_a ![]() |
---|---|---|
A![]() |
500 ![]() |
0 ![]() |
B![]() |
400 ![]() |
100 ![]() |
C ![]() |
250 ![]() |
250 ![]() |
D ![]() |
100 ![]() |
400 ![]() |
My query so far: select product, avg_rev, lag(avg_rev,1) over (order by product) as previous_value from product;
到目前为止我的查询:
select product, avg_rev, lag(avg_rev,1) over (order by product) as previous_value from product;
I can take difference between previous row minus current row by saying previous_value-avg_rev
but what I need is for previous row to be constant, minus current row as carried over all the way.我可以通过说
previous_value-avg_rev
来获取前一行减去当前行之间的差异,但我需要的是前一行保持不变,减去当前行一直沿用。
You need the difference of avg_rev
of the 1st product with the current row's avg_rev
:您需要第一个产品的 avg_rev 与当前行的
avg_rev
的avg_rev
:
SELECT product,
avg_rev,
FIRST_VALUE(avg_rev) OVER (ORDER BY product) - avg_rev AS diff_a
FROM product;
See the demo .请参阅演示。
Results:结果:
product![]() |
avg_rev ![]() |
diff_a ![]() |
---|---|---|
A![]() |
500 ![]() |
0 ![]() |
B![]() |
400 ![]() |
100 ![]() |
C ![]() |
250 ![]() |
250 ![]() |
D ![]() |
100 ![]() |
400 ![]() |
If you specifically want one of the products, I would use conditional logic:如果您特别想要其中一种产品,我会使用条件逻辑:
select product, avg_rev,
avg_rev - max(case when product = 'A' then avg_rev end) over () as diff_a
from product;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.