我有一个表,其中包含ItemCode和库存数量,另一个表中包含采购。
我想要一个查询来获取库存数量(例如,数量= 5),取采购表,降序取采购发票,取商品价格。查询必须根据数量从Purchase表中检索记录,直到库存数量之和=5.ex.
**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)
有没有什么建议。提前谢谢你

发布于 2013-12-11 16:56:53
这个脚本应该可以完成这项工作。
/* 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 */发布于 2013-12-11 17:41:22
Hi这可能是解决方案:在这里我使用了结果表,它将存储结果。我已经使用了三个表Stock(ItemCode,ItemCode,Purchage(PurchageNo,),Stock(ItemCode,ItemCode)和QtyInStock完整的可行代码在这里:
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 #PurchageTemphttps://stackoverflow.com/questions/20514100
复制相似问题