我有下表:
ID | Transaction | Amount | Inventory | Price |
---|---|---|---|---|
1 | NULL | NULL | 11 | NULL |
2 | Sale | -1 | 10 | 100 |
3 | Purchase | 2 | 12 | 102 |
4 | Sale | -2 | 10 | 103 |
第一行是起始金额,下面三行显示更改库存的交易记录.我需要计算一个新的运行平均价格的基础上购买和复制当前的平均价格的情况下销售基于以下公式:
If Transaction = NULL (i.e. starting line) then Average = 90;
If Transaction = 'Sale' then Average = lag(Average) (i.e. whatever is the latest calculated average);
If transaction = 'Purchase' then ((Inventory - Amount) * lag(Average)
+ Amount * Price)
/ Inventory
排序顺序为ID列升序.
这个问题是由滞后(平均值)引起的,因 for each 计算步骤都要求前一行是更新的值,即计算必须逐行运行和更新.
结果表应如下所示:
ID | Transaction | Amount | Inventory | Price | Average |
---|---|---|---|---|---|
1 | NULL | NULL | 11 | NULL | 90 |
2 | Sale | -1 | 10 | 100 | 90 |
3 | Purchase | 2 | 12 | 102 | 92 |
4 | Sale | -2 | 10 | 103 | 92 |
计算如下:
ID 1-->;90(起始值)
ID 2-->;90(复制以前的平均值)
ID3-->;92=((12-2)*90+(2*102))/12
ID 4-->;92(复制以前的平均值)
我try 了以下几种方法:
- 使用起始值为90的列(Average),并在另一列(Average_F)中运行计算.
Select *,
case when [transaction] is null then Average
when [transaction] = 'Sale' then lag(Average) over (order by ID)
when [transaction] = 'Purchase'
then (((Inventory - Amount) * lag(Average) over (order by ID))
+ (Amount * Price)) / Inventory
end as Average_f
from table
没有成功:
ID | Transaction | Amount | Inventory | Price | Average | Average_f |
---|---|---|---|---|---|---|
1 | NULL | NULL | 11 | NULL | 90 | 90 |
2 | Sale | -1 | 10 | 100 | NULL | 90 |
3 | Purchase | 2 | 12 | 102 | NULL | NULL |
4 | Sale | -2 | 10 | 103 | NULL | NULL |
- 我也试过更新声明:
update table
set average = case when [transaction] is null then Average
when [transaction] = 'Purchase'
then (((Inventory - Amount) * (select lag(Average) over (order by ID)
from table t
where t.ID = table.ID))
+ (Amount * Price)) / Inventory
when [transaction] = 'Sale' then (select lag(Average) over (order by ID)
from table t
where t.ID = table.ID)
end
也没有奏效:
ID | Transaction | Amount | Inventory | Price | Average |
---|---|---|---|---|---|
1 | NULL | NULL | 11 | NULL | 90 |
2 | Sale | -1 | 10 | 100 | NULL |
3 | Purchase | 2 | 12 | 102 | NULL |
4 | Sale | -2 | 10 | 103 | NULL |
在SQL中,有没有一种方法可以单独计算每一行,或者有任何其他方法可以使用以前的平均值来计算平均值?