当前位置:Gxlcms > 数据库问题 > SQL 流水账余额查询

SQL 流水账余额查询

时间:2021-07-01 10:21:17 帮助过:12人阅读

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 流水账余额查询

标签:values   es2017   style   images   test   自增字段   http   不重复   creat   

人气教程排行