我有两个临时表,都是由TSQL查询填充的。
临时表包含位置、项目和总库存数量的。
临时表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 |6DEF将被输出到表C中,因为在减去ABC订单后,没有足够的库存来填充订单。
我怎样才能做到这一点?
发布于 2010-09-02 20:36:09
您可以使用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通过10 - 11 = 1超过其项目1库存。
https://stackoverflow.com/questions/3630852
复制相似问题