更好地理解你一旦修正公式。 在這種情況下獲得計算列的先前值並不容易
因此,我們可以將計算列轉換爲臨時表上的物理列並稍後使用它。
此代碼的工作原理,但我認爲不是一個好的解決方案。如果舊的記錄不改,我建議你打開buyAvg新的物理列,它是計算並插入
更新的查詢
select *, cast(null as Decimal(18,2)) as buyavg into #temp from dbo.YourTable where 1=2
;
DECLARE @id int
DECLARE @previd int
DECLARE @prvBuyAvg decimal(18,2)
DECLARE @prvKcode int
DECLARE db_cursor CURSOR FOR
SELECT Id, LAG(Id) OVER (ORDER BY Kcode,datee,id) prevId
FROM dbo.YourTable
order by Kcode,datee,id
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @id, @previd
WHILE @@FETCH_STATUS = 0
BEGIN
select @prvKcode = Kcode, @prvBuyAvg = buyAvg
from #temp where id = @previd
insert into #temp ([Id], [date], [Kcode] , [InOrder] , [pIn] , [SumIn] , OutOrder , pOut , SumOut , stock , LastStock , buyavg)
select [Id], [date], [Kcode] , [InOrder] , [pIn] , [SumIn] , OutOrder , pOut , SumOut , stock , LastStock ,
case
when lastStock = 0 then
pIn
else
case
when InOrder = 0 then
case
when @prvKcode = Kcode then
@prvBuyAvg
else
0
end
else
case
when @prvKcode = Kcode then
((sumIn) + (LastStock*@prvBuyAvg))/(inOrder+LastStock)
else
pIn
end
end
end as newbuyAvg
from dbo.YourTable where id = @id
FETCH NEXT FROM db_cursor INTO @id, @previd
END
CLOSE db_cursor
DEALLOCATE db_cursor
;
select * from #temp
;
buyAvg配方中它寫一個好主意並不清楚(它似乎與評論混在一起)。你能解決這個問題,請 – missionMan