SQL 流水账余额查询

Posted Li Essay

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL 流水账余额查询相关的知识,希望对你有一定的参考价值。

创建表

CREATE TABLE [dbo].[test](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [RQ] [date] NULL,
    [SR] [int] NULL,
    [ZC] [int] NULL
) ON [PRIMARY]

插入数据

INSERT INTO [dbo].[test]([RQ],[SR],[ZC])
VALUES(\'2017-10-01 00:00:00\',30,NULL);
INSERT INTO [dbo].[test]([RQ],[SR],[ZC])
VALUES(\'2017-10-02 00:00:00\',NULL,20);
INSERT INTO [dbo].[test]([RQ],[SR],[ZC])
VALUES(\'2017-10-03 00:00:00\',20,NULL);
INSERT INTO [dbo].[test]([RQ],[SR],[ZC])
VALUES(\'2017-10-04 00:00:00\',NULL,10);
INSERT INTO [dbo].[test]([RQ],[SR],[ZC])
VALUES(\'2017-10-06 00:00:00\',40,NULL);

日期字段不重复

DECLARE @starDate DATE
DECLARE @endDate DATE
SET @starDate = \'2017-10-02\'
SET @endDate = \'2017-10-07\'

SELECT \'期初\' AS 日期, ISNULL(SUM(SR), \'-\') AS 收入, ISNULL(SUM(ZC), \'-\') AS 支出, ISNULL(SUM(SR) -SUM(ZC), \'-\') AS 余额
FROM   test
WHERE  RQ < @starDate
UNION ALL
SELECT CAST(t.RQ AS NVARCHAR), ISNULL(t.SR, 0), ISNULL(t.ZC, 0), ISNULL(
           (
               SELECT SUM(t2.SR) -SUM(t2.ZC)
               FROM   test AS t2
               WHERE  t2.RQ <= t.RQ
           ),0)
FROM   test AS t
WHERE  t.RQ >= @starDate AND t.RQ <= @endDate
UNION ALL
SELECT \'合计\', SUM(SR)SR, SUM(ZC)ZC, SUM(SR) -SUM(ZC)
FROM   test

日期不唯一, 用自增字段来区分:

DECLARE @starDate DATE
DECLARE @endDate DATE
SET @starDate = \'2017-10-02\'
SET @endDate = \'2017-10-07\'

SELECT CAST(\'期初\' AS VARCHAR) AS 序号,\'\' AS 日期, ISNULL(SUM(SR), \'-\') AS 收入, ISNULL(SUM(ZC), \'-\') AS 支出, ISNULL(SUM(SR) -SUM(ZC), \'-\') AS 余额
FROM   test
WHERE  RQ < @starDate
UNION ALL
SELECT CAST(t.ID AS VARCHAR),CAST(t.RQ AS NVARCHAR), ISNULL(t.SR, 0), ISNULL(t.ZC, 0), ISNULL(
           (
               SELECT SUM(t2.SR) -SUM(t2.ZC)
               FROM   test AS t2
               WHERE  t2.id <= t.id
           ),0)
FROM   test AS t
WHERE  t.RQ >= @starDate AND t.RQ <= @endDate
UNION ALL
SELECT \'合计\',\'\', SUM(SR)SR, SUM(ZC)ZC, SUM(SR) -SUM(ZC)

以上是关于SQL 流水账余额查询的主要内容,如果未能解决你的问题,请参考以下文章

运行余额的sql查询

SQL 连接查询以获取借方余额不等于 0 的借方余额的项目名称、日期和总和?

在 SQL 查询中结转/结转余额

sql 银行账户查询余额

SQL查询以跟踪新订单或旧订单中的余额变化,没有日期

一种登记账后余额的处理方法