update table set 数量=(select sum(数量+变量) from table where id<a.id and  产品=a. 产品)
from table a

解决方案 »

  1.   

    按你的数据规律
    改改lsxaa(小李铅笔刀)的语句
    update table 
    set 数量=(select sum(数量+变量) from table where id=a.id-3 and  产品=a. 产品)
    from table a
      

  2.   

    update tablename 
    set 数量 = 数量 +        
               case 产品 
                 when 'A' then 
                     case 数量 
                        when 1 then 1
                        when 2 then 0
                        else 0
                     end
                 when 'B' then
                     case 数量
                        when 2 then 2
                        when 4 then 3
                        else 0
                     end
                 else 0
               end
      

  3.   

    update tablename 
    set 数量 = 数量 +  case 产品 when 'A' then 
                     case 数量 
                        when 1 then 1
                        when 2 then 0
                        else 0
                     end
                 when 'B' then
                     case 数量
                        when 2 then 2
                        when 4 then 3
                        else 0
                     end
                 else 0
               end
      

  4.   

    --问题不复杂,注意两个问题--1. 每种产品id最小的数量的不应该更新(即测试数据中id=1,2,3的)
    --2. 楼主没有给出要更新的数量的更新前的值,所以还要考虑null值的处理--所以语句应该如下:
    update a set 数量=(select isnull(sum(数量),0)+isnull(sum(变量),0) from 表 where 产品=a.产品 and id<a.id)
    from 表 a
    where not exists(
    select * from 表 where 产品=a.产品 and id<a.id)
      

  5.   

    --写错一个条件,改一下:update a set 数量=(select isnull(sum(数量),0)+isnull(sum(变量),0) from 表 where 产品=a.产品 and id<a.id)
    from 表 a
    where exists(
    select * from 表 where 产品=a.产品 and id<a.id)
      

  6.   

    --测试数据create table tb(ID int,产品 varchar(10),数量 int,变量 int)
    insert tb select 1,'A',1,1
    union all select 2,'B',2,2
    union all select 3,'C',3,1
    union all select 4,'A',null,0
    union all select 5,'B',null,3
    union all select 6,'c',null,4
    union all select 7,'A',null,2
    union all select 8,'B',null,1
    union all select 9,'C',null,3
    go--更新处理
    update a set 数量=(select isnull(sum(数量),0)+isnull(sum(变量),0) from tb where 产品=a.产品 and id<a.id)
    from tb a
    where exists(
    select * from tb where 产品=a.产品 and id<a.id)--显示结果
    select * from tb
    go--删除测试
    drop table tb/*--测试结果ID          产品         数量          变量          
    ----------- ---------- ----------- ----------- 
    1           A          1           1
    2           B          2           2
    3           C          3           1
    4           A          2           0
    5           B          4           3
    6           c          4           4
    7           A          2           2
    8           B          7           1
    9           C          8           3(所影响的行数为 9 行)
    --*/