CREATE TABLE #ls1(期间 INT,科目 INT,日期 datetime,收入 DECIMAL(9,2),发出 DECIMAL(9,2),余额 DECIMAL(9,2))
INSERT INTO #ls1 VALUES(1,1005, '2009-1-1',NULL,NULL,90)
INSERT INTO #ls1 VALUES(1,1005, '2009-1-10',50,NULL,NULL)
INSERT INTO #ls1 VALUES(1,1005, '2009-1-21',NULL,10,NULL)
INSERT INTO #ls1 VALUES(2,1005, '2009-2-1',70,NULL,NULL)
INSERT INTO #ls1 VALUES(2,1005, '2009-2-20',NULL,20,NULL)
INSERT INTO #ls1 VALUES(1,1006, '2009-1-1',NULL,NULL,80)
INSERT INTO #ls1 VALUES(1,1006, '2009-1-12',40,NULL,NULL)
INSERT INTO #ls1 VALUES(1,1006, '2009-1-21',NULL,10,NULL)
INSERT INTO #ls1 VALUES(2,1006, '2009-2-1',70,NULL,NULL)
INSERT INTO #ls1 VALUES(2,1006, '2009-2-20',NULL,20,NULL)
SELECT 期间,科目,日期,收入,发出,
(SELECT ISNULL(SUM(收入),0) - ISNULL(SUM(发出),0) + ISNULL(SUM(余额),0) FROM #ls1 a WHERE a.日期<=#ls1.日期
AND a.科目=#ls1.科目)
FROM #ls1 ORDER BY 科目,日期
---------------------------------------------
结果
1
1005
2009-01-01 00:00:00.000
NULL
NULL
90.00
1
1005
2009-01-10 00:00:00.000
50.00
NULL
140.00
1
1005
2009-01-21 00:00:00.000
NULL
10.00
130.00
2
1005
2009-02-01 00:00:00.000
70.00
NULL
200.00
2
1005
2009-02-20 00:00:00.000
NULL
20.00
180.00
1
1006
2009-01-01 00:00:00.000
NULL
NULL
80.00
1
1006
2009-01-12 00:00:00.000
40.00
NULL
120.00
1
1006
2009-01-21 00:00:00.000
NULL
10.00
110.00
2
1006
2009-02-01 00:00:00.000
70.00
NULL
180.00
2
1006
2009-02-20 00:00:00.000
NULL
20.00
160.00