[英]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.