SQL查询检索最后的记录,直到购买的数量达到库存总量

时间:2013-12-11 08:28:23

标签: sql

我有一个包含库存中的ItemCode和Quantity的表以及包含购买的另一个表。

我想要一个查询来获取库存数量(例如数量= 5)并采购购买表以降序获取采购发票并获取商品价格。 查询必须根据数量继续从Purchase表中检索记录,直到我们达到库存数量= 5的总和。 恩。

**Purchase No   ItemCode   Qty   Cost Price**

    2             123       2       100
    3             123       10      105 
    6             123       2       100 
    8             123       1        90
    9             123       2       120 

---------------------------------------------

**ItemCode     Qty in Stock**

    123             5

--------------------------------------------

在这个例子中,我想让查询为我检索最后3张发票(9,8和6),因为数量(2 + 1 + 2 = 5)

有什么建议吗? 提前谢谢

enter image description here

2 个答案:

答案 0 :(得分:0)

这个脚本可以完成这项工作。

/* SQL SCRIPT BEGIN */


create table #tmp (PurchaseNo int, ItemCode int, Qty int)


insert into #tmp (PurchaseNo, ItemCode, Qty)


select 

p1.PurchaseNo, p1.ItemCode, sum(t.Qty) as Qty

from

Purchases p1

join 

(

select 
p2.PurchaseNo, 
p2.ItemCode, p2.Qty 
from
Purchases p2

) t on p1.PurchaseNo <= t.PurchaseNo and p1.ItemCode = t.ItemCode

group by p1.PurchaseNo, p1.ItemCode

order by p1.ItemCode, sum(t.Qty) asc




select * From #tmp
where
ItemCode = 123 
and
Qty < 5 
union
select top 1 * From #tmp
where
ItemCode = 123 
and
Qty >= 5 
order by PurchaseNo desc

drop table #tmp

/* SQL SCRIPT END */

答案 1 :(得分:0)

嗨这可以是解决方案: 这里我使用了结果表来存储结果。 我使用了三个表购买(BuygeNo,ItemCode,Qty),股票(ItemCode,QtyInStock)和结果(PurchageNo)。 完整可行代码在这里:

DECLARE @ItemCode int; 
DECLARE @AvailableQty int; 
SET @ItemCode = 123 ; 
SET @AvailableQty = (select QtyInStock from Stock where ItemCode = @ItemCode); 
SELECT 
    RowNum = ROW_NUMBER() OVER(ORDER BY PurchageNo),*   
INTO #PurchageTemp
FROM Purchage

DECLARE @MaxRownum INT;
SET @MaxRownum = (select COUNT(*)from #PurchageTemp);

DECLARE @Iter INT;
SET @Iter = 1;
DECLARE @QtySum int=0; 
DECLARE @QtySumTemp int=0; 
DECLARE @CurrentItem int; 
WHILE (@Iter <= @MaxRownum and @QtySum <= @AvailableQty)
BEGIN
set @QtySumTemp=@QtySum;
set @QtySumTemp = @QtySumTemp + (SELECT Qty FROM #PurchageTemp WHERE RowNum = @Iter and ItemCode=@ItemCode);
IF @QtySumTemp <= @AvailableQty 
BEGIN
set @QtySum=@QtySumTemp;
  set @CurrentItem= (SELECT PurchageNo FROM #PurchageTemp WHERE RowNum = @Iter and ItemCode=@ItemCode);
              insert into [Result] values (@CurrentItem);
END
              SET @Iter = @Iter + 1
END
DROP TABLE #PurchageTemp