如果您对 AVCO Perpetual方法一无所知,请在阅读问题之前阅读this article或this one:
为了更清楚,我把我的数据放在我的交易表中:
数量列包含已购买或出售的商品数量(负数表示销售发票)
我需要在SQL Server中编写一个返回如下记录集的查询:
成本列包含根据AVCO Perpetual方法计算的交易时产品成本
以下是生成表和数据所需的查询:
CREATE TABLE [dbo].[Transactions]
(
[Id] [INT] NOT NULL ,
[Date] [DATE] NOT NULL ,
[Coefficient] [INT] NOT NULL ,
[Quantity] [INT] NOT NULL ,
[Price] [INT] NOT NULL ,
[Cost] [REAL] NOT NULL ,
CONSTRAINT [PK_Transactions] PRIMARY KEY CLUSTERED ( [Id] ASC )
WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
)
ON [PRIMARY]
GO
INSERT [dbo].[Transactions]
( [Id], [Date], [Coefficient], [Quantity], [Price], [Cost] )
VALUES ( 1, '2017-01-01', 1, 10, 100, 100 ),
( 2, '2017-01-02', 1, 20, 120, 113.33 ),
( 3, '2017-01-03', -1, 5, 200, 113.33 ),
( 4, '2017-01-04', 1, 10, 150, 123.8 ),
( 5, '2017-01-05', -1, 3, 200, 123.8 ),
( 6, '2017-01-06', -1, 10, 200, 123.8 ),
( 7, '2017-01-07', 1, 10, 180, 141.36 ),
( 8, '2017-01-07', -1, 5, 220, 141.36 )
更新
只是简要了解我如何计算成本字段:
((PreviousCost*PreviousStock)+(CurrentPrice*CurrentQuantity))/CurrentStock
答案 0 :(得分:1)
以下查询将满足您的需求。
CREATE TABLE #Temp
(
Date1 DATE,
AvgCost decimal(18,4)
)
DECLARE @QTY FLOAT,
@QTY1 FLOAT,
@Price FLOAT,
@Date DateTime,
@Cost FLOAT,
@Cost1 FLOAT,
@RoundCost FLOAT
SELECT @Cost = 0, @QTY = 0, @RoundCost=0
DECLARE Cur_ CURSOR FOR
SELECT [Date], [Coefficient]*[Quantity], [Price], ([Quantity] * [Price])
FROM [dbo].[Transactions]
ORDER BY [Date] ASC, [Coefficient] DESC
OPEN Cur_
FETCH NEXT FROM Cur_ INTO @Date, @QTY, @Price, @Cost
WHILE @@FETCH_STATUS = 0
BEGIN
IF(@QTY > 0)
BEGIN
SELECT @Cost = @Cost + @RoundCost
END
ELSE
BEGIN
SELECT @Cost = (@Cost1 * (@QTY+@QTY1))
END
SELECT @QTY = @QTY + ISNULL(SUM([Coefficient]*[Quantity]),0) FROM [dbo].[Transactions]
WHERE [Date] < @Date
--SELECT @Date, @QTY, @Price, @Cost, @Cost / @QTY
INSERT INTO #Temp
SELECT @Date, @Cost / @QTY
SET @Cost1 = @Cost / @QTY
SET @QTY1 = @QTY
SET @RoundCost = @Cost
FETCH NEXT FROM Cur_ INTO @Date, @QTY, @Price, @Cost
END
CLOSE Cur_
DEALLOCATE Cur_
SELECT * FROM #Temp T
DROP TABLE #Temp
输出:
(1 row(s) affected)
Date1 AvgCost
---------- ---------------------------------------
2017-01-01 100.0000
2017-01-02 113.3333
2017-01-03 113.3333
2017-01-04 123.8095
2017-01-05 123.8095
2017-01-06 123.8095
2017-01-07 141.3690
2017-01-07 224.5273
(8 row(s) affected)