with wsp
as
(
    select px=row_number() over(order by 编码,进货日期 desc),* from 库存表
)
update m
set 库存 = case when (select sum(库存) from wsp where 编码 = m.编码 and px <= m.px) < n.销售数量 then 0
                when (select sum(库存) from wsp where 编码 = m.编码 and px <= m.px) >= n.销售数量 and
     isnull((select sum(库存) from wsp where 编码 = m.编码 and px < m.px),0) < n.销售数量 then
            (select sum(库存) from wsp where 编码 = m.编码 and px <= m.px) - n.销售数量
                else m.库存
           end
from 销售表 n,wsp m
where m.编码 = n.编码
有谁帮我解释这个更新语句吗 set 库存= 是怎么算的

解决方案 »

  1.   

    with wsp
    as
    (
        select px=row_number() over(order by 编码,进货日期 desc),* from 库存表
    )
    --是SQL2005的CTE,递归调用生成的表
    update m
    set 库存 = case when (select sum(库存) from wsp where 编码 = m.编码 and px <= m.px) < n.销售数量 then 0
                    when (select sum(库存) from wsp where 编码 = m.编码 and px <= m.px) >= n.销售数量 and
         isnull((select sum(库存) from wsp where 编码 = m.编码 and px < m.px),0) < n.销售数量 then
                (select sum(库存) from wsp where 编码 = m.编码 and px <= m.px) - n.销售数量
                    else m.库存
               end
    from 销售表 n,wsp m
    where m.编码 = n.编码--Set= case when...是Case when语句
    如:
    CASE     WHEN Sex= '1' THEN '男'
             WHEN Sex='2' THEN '女'
    ELSE '其他' END
      

  2.   

    先用CTE排序然后用case when 判断累加值
      

  3.   

    如果
    select px=row_number() over(order by 编码,进货日期 desc),* from 库存表
    中编码与销售表相同且进货日期大于销售日期的前提下/*
    1、合计库存比销售数量少,库存为0
    2、合计库存大于等于销售数量( 进货日期大于销售日期) 小于销售数量,库存为 进货日期大于等于销售日期的库存减去销售数量
    3、库存即为当前库存
    */
       
      

  4.   

    insert into 库存表 values('001' , 10 , '2008-03-01') 
    insert into 库存表 values('001' , 16 , '2008-03-02') 
    insert into 库存表 values('001' , 29 , '2008-03-03') 
    insert into 库存表 values('002' , 12 , '2008-03-08') 
    insert into 库存表 values('002' , 15 , '2008-03-09') 比如这张表  ,  001销售 30 个  , 按先进先出,得到001    0    '2008-03-01'
    001    0    '2008-03-01'
    001    22    '2008-03-01'是怎么挨个的减的呢?
      

  5.   

    and
         isnull((select sum(库存) from wsp where 编码 = m.编码 and px < m.px),0) < n.销售数量 then
      

  6.   

    请问 SQL2005的CTE,递归调用生成的表with wsp
    as
    (
        select px=row_number() over(order by 编码,进货日期 desc),* from 库存表
    )是不是跟用临时表一样的啊