2017-11-18 127 views
2

我有這些列的視圖:訪問別名值在SQL Server 2012中

id date Kcode InOrder pIn SumIn OutOrder pOut SumOut stock LastStock 

這一觀點由kCode, date, id返回的所有商品訂單in/out。它工作得很好,但我需要一個新的列,以此公式返回每行的平均成本:

buyAvg = 
    if lastStok = 0 
    then buyAvg = pIn 
    else 
     if InOrder = 0 then 
      if prev record Kcode = Kcode 
      then buyAvg = Prev Record buyAvg 
      else buyAvg = 0 

     if InOrder <> 0 then 
     if prev record Kcode = Kcode 
      then buyAvg = ((sumIn) + (LastStok*Prev Record buyAvg))/(inOrder+LastStock) 
      else buyAvg = pIn 
    end 

謝謝。

我需要一個像一個視圖在這個截圖計算BuyAvg

enter image description here

+0

buyAvg配方中它寫一個好主意並不清楚(它似乎與評論混在一起)。你能解決這個問題,請 – missionMan

回答

0

更好地理解你一旦修正公式。 在這種情況下獲得計算列的先前值並不容易

因此,我們可以將計算列轉換爲臨時表上的物理列並稍後使用它。

此代碼的工作原理,但我認爲不是一個好的解決方案。如果舊的記錄不改,我建議你打開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 
; 
+0

感謝MissionMan –

+0

您好您的代碼不會在其他條件返回True結果.... –

+0

返回0 –