[英]How to pass the value of previous row to current row?
如何将上一行的结果传递给当前行的计算
给定单位和成本,我需要获取每笔交易的平均成本:
公式:
| Row | Type | Unit | Cost | TrxCost | Ave_cost | | 1 |Sub | 0.2 | 1000 | 1000 | 1000 | | 2 |Sub | 0.3 | 2500 | 2500 | 3500 | | 3 |Sub | 0.1 | 600 | 600 | 4100 | | 4 |Red |- 0.2 |-1100 | -1366.67 | 2733.33 | | 5 |Sub | 0.3 | 1000 | 1000 | 3733.33 | | 6 |Red | -0.6 | -600 | -3200 | 533.33 |
更新:
订单基于行号。
谢谢。
您可以使用递归CTE
WITH cte (row_num,
type,
unit,
sum_of_unit,
cost,
trxcost,
ave_cost
) AS (
SELECT row_num,
type,
unit,
unit AS sum_of_unit,
cost,
cost AS trxcost,
cost AS ave_cost
FROM t
WHERE row_num IN (
SELECT MIN(row_num)
FROM t
)
UNION ALL
SELECT t.row_num,
t.type,
t.unit,
c.sum_of_unit + t.unit AS sum_of_unit,
t.cost,
CASE t.type
WHEN 'Sub' THEN t.cost
WHEN 'Red' THEN t.unit * ( c.ave_cost / c.sum_of_unit )
END
AS trxcost,
c.ave_cost + CASE t.type
WHEN 'Sub' THEN t.cost
WHEN 'Red' THEN t.unit * ( c.ave_cost / c.sum_of_unit )
END AS ave_cost
FROM t
JOIN cte c ON t.row_num = c.row_num + 1
)
SELECT * FROM cte
您可以theTrxCost
执行此操作:一次获取theTrxCost
,然后一次获取Ave_cost
。
顺便说一句,您所说的“平均”是一个总计。 您只是在增加价值。
您需要带有ROWS BETWEEN
子句的窗口函数。 (在SUM(...) OVER (ORDER BY ...)
情况下,这隐含在BETWEEN UNBOUNDED PRECEDING AND CURRENT
,但是)。
select
id, type, unit, cost, round(trxcost, 2) as trxcost,
round(sum(trxcost) over (order by id), 2) as ave_cost
from
(
select
id, type, unit, cost,
case
when type = 'Sub' then cost
else
unit *
sum(cost) over (order by id rows between unbounded preceding and 1 preceding) /
sum(unit) over (order by id rows between unbounded preceding and 1 preceding)
end as trxcost
from mytable
)
order by id;
我将您的row
id
重命名,因为ROW
是保留字。
最后一行的结果与您的不同。 我使用了您的公式,但是得到了不同的数字。
Rextester演示: https ://rextester.com/ASXFY4323
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.