SQL 流水賬余額查詢
阿新 • • 發佈:2017-10-29
創建 數據 reat com eight es2017 .cn insert rim
創建表
CREATE TABLE [dbo].[test]( [id] [int] IDENTITY(1,1) NOT NULL, [RQ] [date] NULL, [SR] [int] NULL, [ZC] [int] NULL ) ON [PRIMARY]
插入數據
INSERT INTO [demo].[dbo].[test]([id],[RQ],[SR],[ZC]) VALUES(1,‘2017-10-01 00:00:00‘,30,NULL); INSERT INTO [demo].[dbo].[test]([id],[RQ],[SR],[ZC]) VALUES(2,‘2017-10-02 00:00:00‘,NULL,20); INSERT INTO [demo].[dbo].[test]([id],[RQ],[SR],[ZC]) VALUES(3,‘2017-10-03 00:00:00‘,20,NULL); INSERT INTO [demo].[dbo].[test]([id],[RQ],[SR],[ZC]) VALUES(4,‘2017-10-04 00:00:00‘,NULL,10); INSERT INTO [demo].[dbo].[test]([id],[RQ],[SR],[ZC]) VALUES(5,‘2017-10-06 00:00:00‘,40,NULL);
日期字段不重復
SELECT t.RQ, t.SR, t.ZC, (SELECT SUM(SR) -SUM(ZC) FROM test WHERE rq <= t.rq ) AS 余額 FROM test AS t
日期不唯一, 用自增字段來區分:
SELECT t.ID,t.RQ, t.SR, t.ZC, ( SELECT SUM(SR) -SUM(ZC) FROM test WHERE ID <= t.id ) AS 余額 FROM test AS t
效果
SQL 流水賬余額查詢