需求场景:
现有表记录了每月的金额,如何统计每月金额等于之前的所有月份金额累计:
例:
1月份:100元;
2月份:100元;
3月份:200元;
则期望得到结果:
1月份:1月100元;
2月份:1月 + 2月 = 100 + 100 = 200元;
3月份:1月 + 2月 + 3月 = 100 + 100 + 200 = 400元;
建表:
CREATE TABLE [dbo].[test] ( [id] bigint NOT NULL, [name] varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, [day_month] date NULL, [amount] decimal(19,2) NULL, CONSTRAINT [PK__test__3213E83F38212A42] PRIMARY KEY CLUSTERED ([id])WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[test] SET (LOCK_ESCALATION = TABLE)
数据:
INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10001, 'aaa', '2022-01-01', 100.00);INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10002, 'bbb', '2022-02-01', 100.00);INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10003, 'ccc', '2022-03-01', 100.00);INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10004, 'ddd', '2022-04-01', 200.00);INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10005, 'eee', '2022-05-01', 100.00);INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10006, 'fff', '2022-06-01', 300.00);
按月逐级累计查询语句:
SELECT a.day_month, SUM(b.amount) FROM(SELECT day_month, SUM(amount) amount FROM test GROUP BY day_month) aINNER JOIN(SELECT day_month, SUM(amount) amount FROM test GROUP BY day_month) bON a.day_month >= b.day_monthGROUP BY a.day_monthORDER BY a.day_month
查询结果:
END~
喜欢的请看官一键三连哦
来源地址:https://blog.csdn.net/qq_26878363/article/details/127852738