MYSQL按月累計求和及歷史最大值問題

2021-09-11 18:09:12 字數 2873 閱讀 4339

有以下資料,求每人每月總收入,其累計收入(即本月及其以前月份的累計收入),以及最大收入(本月及其以前月份的收入最大值):

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 tablet_user(

idint(11) not null auto_increment,

usernamevarchar(50) not null,

monthvarchar(50) not null,

salarydecimal(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

參考:

Oracle按月份累計求和

原表 select to char reg date,yyyy mm regdate,count count from ep info t where 1 1 and t.reg date to date 2013 02 yyyy mm and t.reg date to date 2014 05 ...

最值 求和 計數及巢狀使用

最值求和 列舉 最值求和 列舉1.二維字首和 思路 將字首算好,然後用整塊減掉多的再加重複。注意點 字首計算的塊值需要將x 1和y 1和當前的值再減去重複部分。include using namespace std long long a 1001 1001 n,m,q,x1,yn1,x2,y2,i...

MySQL歷史,名稱由來及版本

瑞典的mysql ab創立於1995年,從事製造及擁有關聯式資料庫管理系統mysql以及相關的產品,如mysql cluster,是全球最大的開放原始碼公司。2008年1月16日mysql ab宣布,同意被昇陽微系統 sun microsystems 以約十億美元收購。收購已於2008年2月26日完...