數據庫出貨加權平均成本計算問題

今天同事有個問題如下:

經過多重方案嘗試,最後選擇了 while 循環,歡迎大家提供更優質的方案

代碼如下:

--CREATE DATABASE TEST
--GO
--USE TEST
--GO
--create table test
--(
--Style char,
--Color NVARCHAR(8),
--Size char,
--Price decimal(10,2),
--Quantity int,
--InDate DateTime
--)
--GO
--INSERT INTO test VALUES('A','紅色','L',100,100,'2018-01-01')
--INSERT INTO test VALUES('B','藍色','L',50,50,'2018-02-01')
--INSERT INTO test VALUES('A','紅色','L',80,50,'2018-03-01')
--INSERT INTO test VALUES('A','藍色','S',100,100,'2018-04-01')
--INSERT INTO test VALUES('C','紅色','M',10,60,'2018-05-01')
--INSERT INTO test VALUES('A','紅色','L',111,1,'2018-06-01')

 
declare @num int =110
declare @bnum int = @num
declare @index int = 1
declare @result decimal(10,4) = 0
declare @Quantity int
declare @Price int 
declare @wavg decimal(10,4) = 0
while 1=1
begin
	 SELECT @Quantity =Quantity,@Price=Price FROM (SELECT 
		ROW_NUMBER() OVER(ORDER BY InDate ASC) ID,
		Price,
		Quantity 
	 FROM test where Style='A' and Color = '紅色' AND Size ='L') TEMP WHERE ID = @index
	    if @num < @Quantity
		begin	 
		    set @result =  @result + @num * @Price
			print @result  
			break
		end 
		else
		begin
		   set @num = @num - @Quantity  
		   set  @result =  @result + @Quantity * @Price
	    end 
	set @index += 1	
end 
set @wavg= @result / @bnum 
select @wavg wavg

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章