您可以使用遞歸查詢來有效地滿足這個要求。
不要擔心數據類型不匹配您的表,重要的是他們正確地命令。
/*
create table orders (pack_id int, qty int)
insert orders select 4, 500
create table stock (pack_id int, batchno int, qty int, mfgdate int)
insert stock select 4,1,200,1
insert stock select 4,3,1000,2
*/
-- target qty for a pack_id, or set these are SProc params
declare @packid int set @packid = 4
declare @qty int set @qty = 500
;with A as (
select *, rn=ROW_NUMBER() over (order by mfgdate, batchno)
from stock
where pack_id = @packid),
B as (
select pack_id, batchno, qty=case when qty>@qty then @qty else qty end, mfgdate, [email protected], rn
from A
where rn=1
union all
select A.pack_id, A.batchno, case when A.qty>to_go then to_go else A.qty end, A.mfgdate, @qty-A.qty, A.rn
from A
inner join B on A.rn=B.rn+1
where to_go > 0
)
select pack_id, batchno, qty, mfgdate
from B
order by mfgdate asc, batchno asc
第一CTE設置行號,使得第二CTE可以通過他們去順序地(不能在CTE的遞歸部分使用TOP /聚集體);然後第二個收集股票,直到數量滿足
給出一個解釋結果200和300來自哪裏。 – zerkms 2011-02-10 03:31:14
300 xyz02是需要使數量爲500的 – RichardTheKiwi 2011-02-10 03:38:14