求语句:
表结构:id,type,val
数据:  1  a    2
      2  a    23
      3  b    22
      4  a    -5
select `id`,`val`,`余额`??? where type='a';
结果要求:
 1  a    2      2
 2  a    23     25
 4  a    -5    20
可用存储过程但不能用临时表

解决方案 »

  1.   

    select id,type,val,(select sum(val) from yourTable where type=t.type and id<=t.id) as total
    from yourTable t
    where type='a'
      

  2.   

    或者
    select a.id,a.type,a.value,sum(b.val)
    from yourTable a ,yourTable b
    where a.type=b.type and a.id>=b.id
    and a.type='a'
      

  3.   

    select id,word,val,(select sum(val) from t  where id<=b.id and b.word=word ) as '余额'
    from t b
    group by id
    order by word,id
    +------+------+------+------+
    | id   | word | val  | 余额 |
    +------+------+------+------+
    |    1 | a    |    2 |    2 |
    |    2 | a    |   23 |   25 |
    |    4 | a    |   -5 |   20 |
    |    3 | b    |   22 |   22 |
    +------+------+------+------+