select a.*,
       剩余数量=计划数量-( select sum(实绩数量) 
                           from tablename 
                           where 订号=a.订号 and 分号=a.分号 and 支号<=a.支号
                         )
from tablename a

解决方案 »

  1.   


    select *,剩余数量=计划数量-(select sum(实绩数量) from t1 where 订号=a.订号子 and 支号<=a.支号)
    from t1 a
      

  2.   

    --上面的 a.订号子 写错了,应该是: a.订号--测试--测试数据
    create table t1(订号 varchar(10),分号 int,支号 int,计划数量 int,实绩数量 int)
    insert t1 select 'WW000001',0,1,100000,20000
    union all select 'WW000001',0,2,100000,15000
    union all select 'WW000002',0,1,200000,10000
    union all select 'WW000001',0,3,100000,30000
    union all select 'WW000002',0,2,200000,25000
    go--查询
    select *,剩余数量=计划数量-(select sum(实绩数量) from t1 where 订号=a.订号 and 支号<=a.支号)
    from t1 a
    go--删除测试
    drop table t1/*--测试结果订号        分号       支号        计划数量    实绩数量    剩余数量        
    ---------- ----------- ----------- ----------- ----------- ----------- 
    WW000001   0           1           100000      20000       80000
    WW000001   0           2           100000      15000       65000
    WW000002   0           1           200000      10000       190000
    WW000001   0           3           100000      30000       35000
    WW000002   0           2           200000      25000       165000(所影响的行数为 5 行)
    --*/