假設有一數據表有以下數據
序號   物品  數量
1      aaa   10
2      aaa   6
3      aaa   12
.....
我想要得到如下匯總結果序號   物品  數量   匯總
1      aaa   10     10
2      aaa   6      16
3      aaa   12     28
請問如何實現?

解决方案 »

  1.   

    declare @tab table (序号 int,物品 varchar(10),数量 int,汇总 int)
    insert @tab select *,0 from www 
    declare @a int
    set @a=0
    update @tab set 汇总=@a,@a=@a+数量
    select * from @tab
      

  2.   

    drop table 表
    go
    create table 表(序號 int,物品 varchar(20),數量 int)
    insert into 表
    select 1,'aaa',10
    union all select 2,'aaa',6
    union all select 3,'aaa',12select a.*,(select sum(數量) from 表 b where a.物品=b.物品 and b.序號<=a.序號) as '匯總'
    from 表 a/*
    序號          物品                   數量          匯總          
    ----------- -------------------- ----------- ----------- 
    1           aaa                  10          10
    2           aaa                  6           16
    3           aaa                  12          28(所影响的行数为 3 行)*/