我有一个包含3列的表格:
Name
department
salary
如何确定使用一个查询在每个salary
中找到第三高department
?
答案 0 :(得分:3)
一种方法是LIMIT
一个相关的子查询,但它不是特别有效:
SELECT department, (
SELECT salary
FROM my_table t2
WHERE t2.department = t1.department
ORDER BY salary DESC
LIMIT 2, 1
)
FROM my_table t1
GROUP BY department
答案 1 :(得分:3)
除了eggyal的优秀答案之外,这里还有一个查询,它将为您提供薪水等于第三名(在每个部门)的名字:
SELECT
t.name, t.department, t.salary AS third_salary
FROM
( SELECT DISTINCT department
FROM tableX
) AS d
JOIN
tableX AS t
ON t.department = d.department
AND t.salary =
( SELECT tt.salary -- notice that this
FROM tableX AS tt -- subquery is
WHERE tt.department = d.department -- exactly the same as
ORDER BY tt.salary DESC -- the one in
LIMIT 1 OFFSET 2 -- @eggyal's answer
) ;
答案 2 :(得分:1)
此RANK问题与此类似: MySQL, Get users rank
我可以这样:
SELECT s.*,
(
SELECT COUNT(*)
FROM salaries si
WHERE si.salary >= s.salary AND si.department = s.department
) AS rank
FROM salaries s
WHERE s.rank = 3
答案 3 :(得分:0)
试试这个:
SELECT name, department, salary
FROM (SELECT name, department, salary, IF(@dept=(@dept:=department), @auto:=@auto+1, @auto:=1) indx
FROM employee e, (SELECT @dept:=0, @auto:=1) A
ORDER BY department, salary DESC ) AS A
WHERE indx = 3;