当前位置:   article > 正文

[SQL] 按月累加逐级统计数据_sql计算月度累计

sql计算月度累计

需求场景:

现有表记录了每月的金额,如何统计每月金额等于之前的所有月份金额累计:

例:

1月份:100元;

2月份:100元;

3月份:200元;

则期望得到结果:

1月份:1月100元;

2月份:1月 + 2月 = 100 + 100 = 200元;

3月份:1月 + 2月 + 3月 = 100 + 100 + 200 = 400元;

建表:

  1. CREATE TABLE [dbo].[test] (
  2. [id] bigint NOT NULL,
  3. [name] varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
  4. [day_month] date NULL,
  5. [amount] decimal(19,2) NULL,
  6. CONSTRAINT [PK__test__3213E83F38212A42] PRIMARY KEY CLUSTERED ([id])
  7. WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
  8. ON [PRIMARY]
  9. )
  10. ON [PRIMARY]
  11. GO
  12. ALTER TABLE [dbo].[test] SET (LOCK_ESCALATION = TABLE)

数据:

  1. INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10001, 'aaa', '2022-01-01', 100.00);
  2. INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10002, 'bbb', '2022-02-01', 100.00);
  3. INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10003, 'ccc', '2022-03-01', 100.00);
  4. INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10004, 'ddd', '2022-04-01', 200.00);
  5. INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10005, 'eee', '2022-05-01', 100.00);
  6. INSERT INTO [dbo].[test] ([id], [name], [day_month], [amount]) VALUES (10006, 'fff', '2022-06-01', 300.00);

按月逐级累计查询语句:

  1. SELECT a.day_month, SUM(b.amount) FROM
  2. (SELECT day_month, SUM(amount) amount FROM test GROUP BY day_month) a
  3. INNER JOIN
  4. (SELECT day_month, SUM(amount) amount FROM test GROUP BY day_month) b
  5. ON a.day_month >= b.day_month
  6. GROUP BY a.day_month
  7. ORDER BY a.day_month

查询结果:

END~

喜欢的请看官一键三连哦 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/950306
推荐阅读
相关标签
  

闽ICP备14008679号