如果你表里面有个自动递增的ID,我可以做到 select id, Total= ( select Count(收入)-Count(支出) from 表 where id<=a.idand ) from 表 a
--建议用触发器 Declare @t Table (Id Int,Proj varchar(10),Income Int,Outcome Int) Insert @t Select 1,'aaaaa',0,0 Union all Select 2,'aaaaa',100,0 Union all Select 3,'aaaaa',200,0 Union all Select 4,'aaaaa',0,50 ------------ Select *, 结存=1000+(Select sum(Income)-Sum(OutCOme) From @t Where Proj=A.Proj and Id<=A.Id) From @t A
select
id,
Total=
(
select Count(收入)-Count(支出) from 表 where id<=a.idand
)
from 表 a
Declare @t Table (Id Int,Proj varchar(10),Income Int,Outcome Int)
Insert @t Select 1,'aaaaa',0,0
Union all Select 2,'aaaaa',100,0
Union all Select 3,'aaaaa',200,0
Union all Select 4,'aaaaa',0,50
------------
Select *,
结存=1000+(Select sum(Income)-Sum(OutCOme) From @t Where Proj=A.Proj and Id<=A.Id)
From @t A