题目
数据
1.薪资累加、月份排名(降序)
select *,
sum(salary) over(partition by id order by month ) sum_salary, # order by记得排序,不然都是总和。
rank() over(partition by id order by `month` desc) rks # 按月份排序,跳跃
from employee
2.去掉最近一个月的,因为月份是按照倒序,所以直接筛选排名第一的就好 ,接着就是按两个字段排序
SELECT t.id, t.`month`, t.sum_salary FROM
(
SELECT id, `month`, salary,
SUM(salary) over(PARTITION BY id ORDER BY `month` ROWS 2 PRECEDING) sum_salary, -- 累加的总薪水
rank() over(PARTITION BY id ORDER BY `month` DESC) ranks -- 排名好去掉最近一个月
FROM employee
) t
WHERE t.ranks > 1
order by id ,`month` desc;