简体   繁体   English

从上一行减去当前行,保持上一行值不变 — SQL

[英]Subtract current row from previous row, keeping previous row value as constant — SQL

Table product has average revenue by product表产品按产品划分的平均收入

product产品 avg_rev avg_rev
A一个 500 500
B 400 400
C C 250 250
D D 100 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 avg_rev diff_a diff_a
A一个 500 500 0 0
B 400 400 100 100
C C 250 250 250 250
D D 100 100 400 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_revavg_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 avg_rev diff_a diff_a
A一个 500 500 0 0
B 400 400 100 100
C C 250 250 250 250
D D 100 100 400 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.

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