赞
踩
建表
DROP TABLE IF EXISTS employee; CREATE TABLE employee ( Id INT, MONTH INT, Salary DECIMAL ); INSERT INTO employee VALUES(1, 1, 20); INSERT INTO employee VALUES(2, 1, 20); INSERT INTO employee VALUES(1, 2, 30); INSERT INTO employee VALUES(2, 2, 30); INSERT INTO employee VALUES(3, 2, 40); INSERT INTO employee VALUES(1, 3, 40); INSERT INTO employee VALUES(3, 3, 60); INSERT INTO employee VALUES(1, 4, 60); INSERT INTO employee VALUES(3, 4, 70);
解题思路
用开窗函数求薪水,对id分组然后根据月份降序排列,需要去掉最近一个月即去掉top1
注意题目要求是三个月的总额,所以要加 ROWS 2 PRECEDING,将当前行和它前面的两行划为一个窗口
SELECT t.id, t.`month`, t.salary FROM
(
SELECT id, `month`,
SUM(salary) over(PARTITION BY id ORDER BY `month` ROWS 2 PRECEDING) salary, -- 累加的总薪水
rank() over(PARTITION BY id ORDER BY `month` DESC) ranks -- 排名好去掉最近一个月
FROM employee
) t
WHERE t.ranks > 1
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。