先进先出的订单分配处理
 
--测试数据
create table ta(物料 varchar(10),批号 varchar(10),库存数 int)
--/*--第一套测试数据
insert ta select 'aa','p01',5
union all select 'aa','p02',10
union all select 'bb','p01',20create table tb(订单 int,物料 varchar(10),订货数 int)
--/*--第一套测试数据
insert tb select 1,'aa',11
union all select 1,'bb',10
union all select 2,'aa',2
union all select 3,'aa',1go
SELECT ROW_NUMBER() OVER (ORDER BY b.物料,a.批号) AS fldID, b.订单,b.物料,a.批号,a.库存数,b.订货数,出库=cast(0 as int)
 ,未分配=cast(null as int),库存结余=cast(null as int),未配订单=cast(null as int),物料2=CAST(NULL AS NVARCHAR(10))
into #t
from ta a,tb b
where a.物料=b.物料
order by b.物料,a.批号,b.订单
--生成出库数据 ---
declare @物料 varchar(10),@批号 varchar(10),@订单 int
declare @出库 int,@库存 int,@未分配 INT,@a INT
update #t SET
---@物料=null @批号=null,@物料='aa' @批号='p01'

 @库存=case when 物料=@物料  then 
case when 批号=@批号 then @库存 else @库存+库存数 end
   else 库存数  end, --每一行 @库存的预计值 -- 5,5,5,15,15,15,20
   
 @出库=case when @库存>0  then 
case when @物料=物料 then 
case when isnull(@订单,订单)<=订单  then 
case when @未分配>0  then 
case when @库存<@未分配 then @库存 else @未分配 end
else case when @库存<订货数 then @库存 else 订货数 end end
else 0 end
 else case when @库存<订货数 then @库存 else 订货数 end end
  else 0 end,     --每一行 @出库的预计值    ----5,  --- 出库=@出库,
  
 @未分配=case when @出库>0  then 
case when @物料=物料 and @未分配>0  then @未分配-@出库   else 订货数-@出库 end
 else @未分配 end, --每一行 @未分配的预计值   ---6,
  
 @订单=case when @物料=物料  then 
case when @出库>0  then 
case when @未分配>0 then 订单 else 订单+1 end
else @订单 end
else case when @未分配>0 then 订单 else 订单+1 end end, --每一行 @未分配的预计值  ----1
  
 @库存=@库存-@出库,    --每一行 @未分配的预计值  ----0
 出库=@出库,   --每一行 @未分配的预计值  ----5
 
 物料2=ISNULL(@物料,'')+ ISNULL(@批号,'')+ CAST(@库存  AS NVARCHAR(10)),
 
 未分配=@未分配,库存结余=@库存,未配订单=@订单,
 @物料=物料,@批号=批号SQL

解决方案 »

  1.   

    这段SQL 反应的是SQL 执行原理,根据原理预测变量值和结果值!!
      

  2.   

    erp订单处理的逻辑了,订单谁先到,谁先满足之
      

  3.   

    我们曾经做过验证,比如A,B两个表
    使用left join ,inner join关联,如:
    ... from A left join B on .....
    ... from A inner join B on .....
    ... from B inner join A on .....
    想验证哪种写法运算快?结果表明运算一样快,为什么呢?微软查询sql语句时已经自动做优化了,
    也就是同步进行,无论where 在哪里?不存在先后顺序
      

  4.   

    #6楼兄弟可能把意思理解错了!我这里问的是where 的问题,
    这个案例的难点是行更新时使用了变量,而变量直接影响了结果值,只有准确的知道变量值才能知道正确的结果! 我为何要求解答者填入每行在更新时的变量值的,就是出于此目的!额外知识点,要回答此问题,必须理解SQL 在做Update 的原理!!