我有两个临时表,都由TSQL查询填充。
临时表A ,其中包含位置,项目和总库存数。
临时表B ,其中包含位置,料品,销售订单号和负库存盘点。
我想循环浏览表B 中的每个项目,并从表A中减去位置和项目匹配的负库存计数。一旦库存达到表B中的< = 0,我想将每个订单输出到第3个表中,该表包含位置,项目和销售订单号。
示例表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 :(得分: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}}的第1项库存。