对于旧版本的 MySQL,您可以使用子查询来完成,在 MySQL 8.0 及更高版本中,您可以使用sum()over() 按公司列分区的窗口函数。
架构和插入语句:
create table company_profit(company varchar(50), year int, profit int );
insert into company_profit values('google', 2019, 16);
insert into company_profit values('google', 2020, 18);
insert into company_profit values('google', 2021, 13);
insert into company_profit values('apple', 2019, 20);
insert into company_profit values('apple', 2020, 26);
insert into company_profit values('apple', 2021, 21);
insert into company_profit values('bp', 2019, 15);
insert into company_profit values('bp', 2020, 10);
insert into company_profit values('bp', 2021, 17);
使用子查询运行总查询(对于 MySQL 8.0 之前的旧版本)
select company,year,profit,
(select sum(profit) from company_profit c where c.company=cp.company and c.year<=cp.year) as cum_profit
from company_profit cp
输出:
| company |
year |
profit |
cum_profit |
| google |
2019 |
16 |
16 |
| google |
2020 |
18 |
34 |
| google |
2021 |
13 |
47 |
| apple |
2019 |
20 |
20 |
| apple |
2020 |
26 |
46 |
| apple |
2021 |
21 |
67 |
| bp |
2019 |
15 |
15 |
| bp |
2020 |
10 |
25 |
| bp |
2021 |
17 |
42 |
使用窗口函数运行总查询(适用于 MySQL 8.0 及更高版本):
select company,year,profit,sum(profit)over( partition by company order by company,year) as cum_profit
from company_profit
输出:
| company |
year |
profit |
cum_profit |
| apple |
2019 |
20 |
20 |
| apple |
2020 |
26 |
46 |
| apple |
2021 |
21 |
67 |
| bp |
2019 |
15 |
15 |
| bp |
2020 |
10 |
25 |
| bp |
2021 |
17 |
42 |
| google |
2019 |
16 |
16 |
| google |
2020 |
18 |
34 |
| google |
2021 |
13 |
47 |
dbhere