您可以使用aubquery來計算運行總數。在外部查詢,您可以指定運行的總金額必須大於總庫存較大:
select location
, item
, [Order]
, TotalInventory
, RunningTotal
from (
select [order].location
, [order].item
, [order].[Order]
, (
select SUM(inventory)
from @a inv
where inv.item = [order].item
and inv.location = [order].location
) as TotalInventory
, (
select SUM(QuantityUsed)
from @b prevorder
where prevorder.item = [order].item
and prevorder.location = [order].location
and prevorder.[order] <= [order].[order]
) as RunningTotal
from @b [order]
) as OrderExtended
where TotalInventory < RunningTotal
測試數據:
declare @a table (item int, location char(1), inventory int)
insert into @a select 1, 'A', 10
union all select 2, 'B', 20
declare @b table ([order] char(3), item int, location char(1), QuantityUsed int)
insert into @b select 'ABC', 1, 'A', 5
union all select 'ZYX', 2, 'B', 10
union all select 'DEF', 1, 'A', 6
此打印:
location item Order TotalInventory RunningTotal
A 1 DEF 10 11
所以爲了DEF導致地點A超過其項目1庫存10 - 11 = 1
。
按照什麼順序循環訪問表B? – Andomar 2010-09-02 20:23:41
按照第一列的順序編號 – 2010-09-02 20:27:24