3

我有一个包含 3 列的表:

Name department salary

如何确定使用一个查询salary在每个查询中找到第三高department

4

4 回答 4

7

一种方法是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
于 2013-01-11T17:26:08.743 回答
5

除了 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
      ) ;
于 2013-01-11T17:33:00.117 回答
2

这个 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
于 2013-01-11T19:05:55.113 回答
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;
于 2013-01-11T17:35:00.413 回答