有多組數據,分別是收入,支出,余額,它們的關系是:
本期余額=上次余額+收入-支出
/* 測試數據: Create Table tbl([日期] smalldatetime,[收入] int ,[支出] int) Insert Into tbl SELECT '2004-02-11', 60, 45 union SELECT '2004-10-01',60, 45 union SELECT '2004-10-02',40, 50 union SELECT '2004-10-15',50, 40 union SELECT '2004-10-16',10, null union SELECT '2004-10-19',10, 0 union SELECT '2004-10-30',0, 10 */
--select *,(select sum(收入-支出) from 表 where 你的表的主鍵<=tem.你的表的主鍵) 本次余額 from 表 tem select t.日期,t.收入,t.支出,(select sum(ISNULL(收入, 0))-sum(ISNULL(支出, 0)) from tbl where 日期 <= t.日期) as 本期余額 from tbl t order by 日期 desc