问题是使用自我联接在emp表中找到第二高的薪水。
代码如下:
SELECT DISTINCT sal FROM emp e1
WHERE 2 = (SELECT count(DISTINCT sal) FROM emp e2 WHERE e1.sal <= e2.sal);
有人可以解释一下此查询工作的机制吗??
答案 0 :(得分:0)
您可以将以下带有相关子查询的查询视为澄清您的问题
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 )
子查询有两个salaries_count,计数值为2,给出了第二高的工资。