2010-09-02 62 views
2

我有兩個臨時表,都由TSQL查詢填充。TSQL循環遍歷表記錄並與第2個表進行比較

溫度表A包含位置,項目和總庫存盤點。

溫度表B包含一個位置,一個項目,一個銷售訂單號碼和負面庫存盤點。

我想遍歷表B中的每個項目,並從位置和項目匹配的表A中減去負數庫存計數。一旦表B中的庫存達到< = 0,我想將每個訂單輸出到保存位置,物料和銷售訂單號的第三個表中。

實施例表A

Item|Location|Inventory 
1 A  10 
2 B  20 

實施例表B

Order|Item|Location|QuanityUsed 
ABC |1 |A  |5 
ZYX |2 |B  |10 
DEF |1 |A  |6 

DEF將被輸出到表C,因爲沒有足夠的廣告來填補減去順序ABC後的順序。

我該如何做到這一點?

+0

按照什麼順序循環訪問表B? – Andomar 2010-09-02 20:23:41

+0

按照第一列的順序編號 – 2010-09-02 20:27:24

回答

2

您可以使用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