如何从不同部门找到第n个最高工资?

时间:2017-07-10 04:38:28

标签: mysql sql

我正在尝试从列表中找到每个部门的第n大薪水。我可以使用聚合来执行基本的最小值和最大值,例如

Select DEPARTMENT, MAX(SALARY) FROM dept_salary
GROUP BY 1  

使用MySQL我可以根据个人而不是合并来获得第n个工资:

SELECT DISTINCT DEPARTMENT, SALARY FROM dept_salary
ORDER BY 2 DESC
LIMIT n,1

DEPARTMENT         SALARY
-------------------------
Customer Service   143937
Human Resources    141953
Customer Service   138637
Customer Service   137535
Customer Service   136548
Customer Service   135650
Marketing          135497
Customer Service   134893
Customer Service   133837
Customer Service   133569

有关如何使其工作的任何指针都非常感谢。

4 个答案:

答案 0 :(得分:2)

对于一般解决方案,变量是最简单的方法:

this.iterationRecords = Ext.create('Rally.data.wsapi.Store', {
        model: 'Iteration',
        fetch: ["Name", START_DATE_FIELD, END_DATE_FIELD, "ObjectID", "State", "PlannedVelocity", "UserStories"], //Having trouble grabbing User Stories
            sorters: [
                {property: START_DATE_FIELD, direction: "DESC"},
                {property: END_DATE_FIELD, direction: "DESC"},
                {property: "State", operator: "=", value: "Accepted"}
            ],
        autoLoad: true,
        listeners: {
            load: function(store, records) {
                console.log(records);
            }
        }
    });

答案 1 :(得分:1)

尝试按部门分组:

SELECT DEPARTMENT, MAX(SALARY) AS max_salary FROM dept_salary
GROUP BY DEPARTMENT
ORDER BY SALARY DESC

答案 2 :(得分:0)

select 
 DISTINCT(salary) 
from dept_salary
 order by salary desc 
limit 1,1

答案 3 :(得分:0)

set @nthMaxSalary = 2;

select ctr,dept,salary from (
select @rowCtr := if(@dept = dept,@rowCtr +1,1) as ctr
,@dept := dept dept
,salary
from dept_salary
order by dept,salary desc
  ) t where ctr = @nthMaxSalary ;