【发布时间】:2019-05-20 15:39:42
【问题描述】:
问题是使用自连接找到emp表的第二高薪水。
代码如下:
SELECT DISTINCT sal FROM emp e1
WHERE 2 = (SELECT count(DISTINCT sal) FROM emp e2 WHERE e1.sal <= e2.sal);
有人可以解释一下这个查询背后的工作机制吗?
【问题讨论】:
标签: sql oracle oracle11g top-n
问题是使用自连接找到emp表的第二高薪水。
代码如下:
SELECT DISTINCT sal FROM emp e1
WHERE 2 = (SELECT count(DISTINCT sal) FROM emp e2 WHERE e1.sal <= e2.sal);
有人可以解释一下这个查询背后的工作机制吗?
【问题讨论】:
标签: sql oracle oracle11g top-n
您可以考虑以下带有相关子查询的查询来澄清您的问题
select ( select max(distinct e2.sal) from emp e2 where e1.sal <= e2.sal ) as max_salary,
( select min(distinct e2.sal) from emp e2 where e1.sal <= e2.sal ) as min_salary,
( select count(distinct sal) from emp e2 where e1.sal <= e2.sal )
as salaries_count
from emp e1
order by salaries_count;
MAX_SALARY MIN_SALARY SALARIES_COUNT
5000 5000 1
5000 3000 2
5000 3000 2
5000 2975 3
5000 2850 4
5000 2450 5
5000 1600 6
5000 1500 7
5000 1300 8
5000 1250 9
5000 1250 9
5000 1100 10
5000 950 11
5000 800 12
不同的薪水数量(reversely_exceeding_salaries"低于最高薪水的不同薪水数量 -> 5000")剩余低于最高薪水加薪作为薪水减少。
( select count(distinct sal) from emp e2 where e1.sal <= e2.sal ) 子查询有两个salary_count,计数值为2,它给出了第二高的薪水。
【讨论】: