state为1的时候是减,0时是加!total就是累加累减得出的结果!

解决方案 »

  1.   

    select *,(select sum(price*case state when 0 then -1 when 1 then 1 end) from tablename where id<=a.id) as total
    from tablename a
    order by id
      

  2.   

    你的例子错了,应该是:
    id       state    price   total
    1 1 100     -100
    2 0 800     700
    3 1 500     200
    4 1 350     -150
    5 0 450     300
      

  3.   

    或者数据应该是:
    id       state    price
    1 0 100
    2 0 800
    3 1 500
    4 1 350
    5 0 450