赞
踩
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 查询员工的累计薪水,我们先来看题面:
https://leetcode-cn.com/problems/find-cumulative-salary-of-an-employee/
https://blog.csdn.net/qq_42363032/article/details/108950022
建表
- 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
- 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 版权所有,并保留所有权利。