MYSQL按月累计求和及历史最大值问题

有以下数据,求每人每月总收入,其累计收入(即本月及其以前月份的累计收入),以及最大收入(本月及其以前月份的收入最大值):
username,month,salary
A,2018/01,5
A,2018/01,15
B,2018/01,5.2
A,2018/01,8.7
B,2018/01,25
A,2018/01,5.7
C,2018/01,10.4
C,2018/01,20
A,2018/02,4
A,2018/02,6
C,2018/02,3.0
C,2018/02,11.6
B,2018/02,10.7
B,2018/02,5
A,2018/03,14
A,2018/03,6.5
B,2018/03,20.9
B,2018/03,25
C,2018/03,10
C,2018/03,20
A,2018/04,14
A,2018/04,6.5
B,2018/04,20.9
B,2018/04,25
C,2018/04,10
C,2018/04,20
A,2018/05,14
A,2018/05,6.5
B,2018/05,20.9
B,2018/05,23.5
C,2018/05,10
C,2018/05,20
A,2018/06,14
A,2018/06,6.5
B,2018/06,20.9
B,2018/06,2.5
C,2018/06,10.98
C,2018/06,20.45

建表:
CREATE TABLE t_user (
id INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
month VARCHAR(50) NOT NULL,
salary DECIMAL(12,6) NOT NULL,
PRIMARY KEY (id)
)
ENGINE=InnoDB
;

导入数据:
insert into t_user(username,month,salary) values
(‘A’,‘2018/01’,5),
(‘A’,‘2018/01’,15),
(‘B’,‘2018/01’,5.2),
(‘A’,‘2018/01’,8.7),
(‘B’,‘2018/01’,25),
(‘A’,‘2018/01’,5.7),
(‘C’,‘2018/01’,10.4),
(‘C’,‘2018/01’,20),
(‘A’,‘2018/02’,4),
(‘A’,‘2018/02’,6),
(‘C’,‘2018/02’,3.0),
(‘C’,‘2018/02’,11.6),
(‘B’,‘2018/02’,10.7),
(‘B’,‘2018/02’,5),
(‘A’,‘2018/03’,14),
(‘A’,‘2018/03’,6.5),
(‘B’,‘2018/03’,20.9),
(‘B’,‘2018/03’,25),
(‘C’,‘2018/03’,10),
(‘C’,‘2018/03’,20),
(‘A’,‘2018/04’,14),
(‘A’,‘2018/04’,6.5),
(‘B’,‘2018/04’,20.9),
(‘B’,‘2018/04’,25),
(‘C’,‘2018/04’,10),
(‘C’,‘2018/04’,20),
(‘A’,‘2018/05’,14),
(‘A’,‘2018/05’,6.5),
(‘B’,‘2018/05’,20.9),
(‘B’,‘2018/05’,23.5),
(‘C’,‘2018/05’,10),
(‘C’,‘2018/05’,20),
(‘A’,‘2018/06’,14),
(‘A’,‘2018/06’,6.5),
(‘B’,‘2018/06’,20.9),
(‘B’,‘2018/06’,2.5),
(‘C’,‘2018/06’,10.98),
(‘C’,‘2018/06’,20.45);

答案:
select t3.username,t3.month,t3.salary,sum(t4.salary) as accumulate,max(t4.salary) as max_salary
from
(select t1.username,t1.month,(t1.salary) as salary
from t_user t1
group by t1.username,t1.month) t3
left join
(select t2.username,t2.month,(t2.salary) as salary
from t_user t2
group by t2.username,t2.month) t4 on t4.month <= t3.month and t4.username = t3.username
group by t3.username,t3.month

参考:https://blog.csdn.net/adayan_2015/article/details/81102950

猜你喜欢

转载自blog.csdn.net/WinSping/article/details/88075147
今日推荐