创建表
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)