我需要找到薪水第三高的人的名字
相关表格如下:
Name Salary Experience
-------------------------------
Den 11000 114
Gerald 11000 148
Ellen 11000 174
Eleni 10500 149
Clara 10500 162
Janette 10000 156
Peter 10000 150
Hermann 10000 204
Harrison 10000 169
我需要找到经验丰富且在薪资排名第三高的人的名字。
因此,显然,第三高的薪水是10000,而在第三高的薪水中,最大经验是赫尔曼,经验值为204。
我要查询以找到第三高的工资:
select name, salary, experience
from sal s1
where 3 - 1 = (select count(distinct salary)
from sal s2
where s2.salary > s1.salary);
但是此查询返回4行,我需要知道如何在同一查询中进一步过滤它以找到exp为204的Hermann。
答案 0 :(得分:3)
使用DENSE_RANK
分析函数找到第三高的薪水,并使用ROW_NUMBER
子句的RANK
(或DENSE_RANK
或PARTITION BY
)分析函数来查找找到薪水最高的经验。只需进行一次表/索引扫描。
Oracle设置:
CREATE TABLE table_name ( Name, Salary, Experience ) AS
SELECT 'Den', 11000, 114 FROM DUAL UNION ALL
SELECT 'Gerald', 11000, 148 FROM DUAL UNION ALL
SELECT 'Ellen', 11000, 174 FROM DUAL UNION ALL
SELECT 'Eleni', 10500, 149 FROM DUAL UNION ALL
SELECT 'Clara', 10500, 162 FROM DUAL UNION ALL
SELECT 'Janette', 10000, 156 FROM DUAL UNION ALL
SELECT 'Peter', 10000, 150 FROM DUAL UNION ALL
SELECT 'Hermann', 10000, 204 FROM DUAL UNION ALL
SELECT 'Harrison', 10000, 169 FROM DUAL
查询:如果要查找“在薪资最高的第三位中拥有丰富经验的人”:
SELECT Name, Salary, Experience
FROM (
SELECT t.*,
DENSE_RANK() OVER ( ORDER BY Salary DESC ) AS s_rank,
ROW_NUMBER() OVER ( PARTITION BY Salary ORDER BY Experience DESC )
AS Exp_rownum
FROM table_name t
)
WHERE s_rank = 3
AND Exp_rownum = 1;
如果您将ROW_NUMBER()
或RANK()
的{{1}}分析功能交换给其他人,如果他们在最高薪水名列第三的同时拥有最高的共同经验,则会返回多个人。 / p>
输出:
NAME | SALARY | EXPERIENCE :------ | -----: | ---------: Hermann | 10000 | 204
查询:如果您想找到“拥有最高经验并且(也)在薪水第三高的人”:
只需执行上面的查询,然后删除DENSE_RANK()
子句即可。
PARTITION BY
输出:
(注意:如果Herman的经验为173,则不会返回任何行,因为Ellen具有最高的经验,但她不会排在第三高薪,而Herman会排在第三高薪,但是只会获得第二高的经验。)
NAME | SALARY | EXPERIENCE :------ | -----: | ---------: Hermann | 10000 | 204
db <>提琴here
答案 1 :(得分:0)
您无需质疑体验。因此,您必须添加一个子句:
select name, salary, experience
from sal s1
where 3 - 1 = (select count(distinct salary)
from sal s2
where s2.salary > s1.salary)
and experience = (select max(experience) from sal)
更新
替代方法(最高经验在第三高薪之内)应该是:
select name, salary, experience
from sal s1
where 3 - 1 = (select count(distinct salary)
from sal s2
where s2.salary > s1.salary)
and experience = (select max(experience) from sal s3
where 3 - 1 = (select count(distinct salary)
from sal s4
where s4.salary > s3.salary)
)
答案 2 :(得分:0)
此查询利用ROWNUM和MAX查找正确的行。在最里面的子查询中,每个薪水级别的最高体验都得到恢复,按薪水降序排列,然后在最外面的子查询中添加行号,并将其与原始表结合以找到正确的行< / p>
SELECT s.name, s.salary, s.experience
FROM sal s
JOIN (SELECT s2.*, ROWNUM rnum
FROM (SELECT salary, max(experience) AS m_exp
FROM sal
GROUP BY salary
ORDER BY salary DESC) s2) s3 ON s3.salary = s.salary AND
s3.m_exp = s.experience AND
rnum = 3