先进先出存货估值

时间:2017-01-25 01:46:01

标签: sql sql-server

我正在使用sql server 2014 ..我的股票交易表是这样的。

declare @Stock table (Item char(3) not null,[Date] datetime not null,TxnType varchar(3) not null,Qty int not null,Price decimal(10,2) null)
insert into @Stock(Item ,  [Date] ,        TxnType, Qty,  Price) values
('ABC','20120401','IN',    200, 750.00),
('ABC','20120405','OUT',   100 ,null  ),
('ABC','20120410','IN',     50, 700.00),
('ABC','20120416','IN',     75, 800.00),
('ABC','20120425','OUT',   175, null  ),
('XYZ','20120402','IN',    150, 350.00),
('XYZ','20120408','OUT',   120 ,null  ),
('XYZ','20120412','OUT',    10 ,null  ),
('XYZ','20120424','IN',     90, 340.00);

我需要在每个月底计算出2个以下的案例。

  1. 剩余数量的库存评估
  2. 输出:

    股票数据的股票估值

    Item  Qty      Value
    ABC   50    40000.00
    XYZ   110   37400.00 
    

    请帮助我在FIFO中获得解决方案

1 个答案:

答案 0 :(得分:1)

Select Item, FinalQty as [Final Qty], CurrPrice*FinalQty as [Current Value] from (
 select Item, Sum(Case When TxnType='OUT' Then -Qty Else Qty End) as FinalQty ,
        (Select Top 1 Price from @Stock where Price is not null and s.Item=Item order by Date Desc) as CurrPrice
 from @Stock s
 group by Item ) n