declare @tb table (name varchar(10),num int)
insert into @tb select 'A',1
insert into @tb select 'A',1
insert into @tb select 'B',1
insert into @tb select 'B',2select *,id=identity(int,1,1) into # from @tb
select name,num,sumnum=case when id=(select max(id) from # where name=tp.name) then (select sum(num) from # where name=tp.name and id<=tp.id) end 
from # tp name num sumnum
A 1 NULL
A 1 2
B 1 NULL
B 2 3

解决方案 »

  1.   

    姓名     数量    总计 
     A        1 
     A        1       2 
     B        1 
     B        2       3 select m.* , n.总计 from tb m,
    (select 姓名,sum(数量) 总计 from tb group by 姓名) n
    where m.姓名 = n.姓名
      

  2.   


    declare @tb table (name varchar(10),num int)
    insert into @tb select 'A',1
    insert into @tb select 'A',1
    insert into @tb select 'B',1
    insert into @tb select 'B',2select *,id=identity(int,1,1) into # from @tbselect * from #select name,num,sumnum
                    =case when id=(select max(id) from # where name=tp.name) 
                          then (select sum(num) from # where name=tp.name and id<=tp.id)
                          end 
    from # tp