赞
踩
需求场景:
现有表记录了每月的金额,如何统计每月金额等于之前的所有月份金额累计:
例:
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]
- GO
-
- ALTER 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) a
- INNER JOIN
- (SELECT day_month, SUM(amount) amount FROM test GROUP BY day_month) b
- ON a.day_month >= b.day_month
- GROUP BY a.day_month
- ORDER BY a.day_month
查询结果:
END~
喜欢的请看官一键三连哦
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。