🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] # 需求 有如下访客访问次数统计表 t_access_times ![](https://box.kancloud.cn/3165335e71b111812f250467a0cdc887_826x377.png) 需要输出报表:t_access_times_accumulate ![](https://box.kancloud.cn/8185e38ae53a36c78fefea116600cff3_823x222.png) # 实现步骤 1. 第一步,先求个用户的月总金额 ~~~ select username,month,sum(salary) as salary from t_access_times group by username,month ~~~ ~~~ +-----------+----------+---------+--+ | username | month | salary | +-----------+----------+---------+--+ | A | 2015-01 | 33 | | A | 2015-02 | 10 | | B | 2015-01 | 30 | | B | 2015-02 | 15 | +-----------+----------+---------+--+ ~~~ 2. 第二步,将月总金额表 自己连接 自己连接 ~~~ select A.*,B.* FROM (select username,month,sum(salary) as salary from t_access_times group by username,month) A inner join (select username,month,sum(salary) as salary from t_access_times group by username,month) B on A.username=B.username where B.month <= A.month ~~~ ~~~ +-------------+----------+-----------+-------------+----------+-----------+--+ | a.username | a.month | a.salary | b.username | b.month | b.salary | +-------------+----------+-----------+-------------+----------+-----------+--+ | A | 2015-01 | 33 | A | 2015-01 | 33 | | A | 2015-01 | 33 | A | 2015-02 | 10 | | A | 2015-02 | 10 | A | 2015-01 | 33 | | A | 2015-02 | 10 | A | 2015-02 | 10 | | B | 2015-01 | 30 | B | 2015-01 | 30 | | B | 2015-01 | 30 | B | 2015-02 | 15 | | B | 2015-02 | 15 | B | 2015-01 | 30 | | B | 2015-02 | 15 | B | 2015-02 | 15 | +-------------+----------+-----------+-------------+----------+-----------+--+ ~~~ 3. 第三步,从上一步的结果中 进行分组查询,分组的字段是`a.username a.month` 求月累计值: 将`b.month <= a.month`的所有`b.salary`求和即可 ~~~ select A.username,A.month,max(A.salary) as salary,sum(B.salary) as accumulate from (select username,month,sum(salary) as salary from t_access_times group by username,month) A inner join (select username,month,sum(salary) as salary from t_access_times group by username,month) B on A.username=B.username where B.month <= A.month group by A.username,A.month order by A.username,A.month; ~~~