1.数据初始化
create DATABASE sql_test;
use sql_test;
create TABLE pay (
id int primary key auto_increment,
date VARCHAR(255),
pay int
);
insert into pay values (1,'2021-01-01',100),
(2,'2021-02-01',100),
(3,'2021-03-01',100),
(4,'2021-04-01',100),
(5,'2021-05-01',100),
(6,'2021-06-01',100);
2.初始表数据如下:
3.累计查询结果如下 :
SQL展示:
select date, (select sum(pay) from pay b where b.date<= a.date) pay from pay a group by id order by date asc;
select b.id,b.date,sum(a.pay) from pay a,pay b where a.date<=b.date group by b.id order by b.date asc;