table = emp
SAL
------
8000
7000
6000
5000
10000
9000
4000
8000
7000
对于上表,编写SELECT语句以显示最大和第二大Sals。您的输出应如下所示: -
first second
------- --------
10000 9000
我写了以下查询,但我得到了以下输出:
select sal from (select rownum first, sal from(select distinct sal from emp1 order by sal desc))where first <= 2;
输出:
SAL
-----
10000
9000
答案 0 :(得分:1)
然后从您自己的请求中选择最小值和最大值,分成两个不同的列。
with i
as ( select sal
from ( select rownum first
, sal
from ( select distinct sal
from scott.emp
order by sal desc ) )
where first <= 2 )
select min ( i.sal )
, max ( i.sal )
from i
group by i.sal;
答案 1 :(得分:1)
另一种方法是使用DENSE_RANK函数;另外,如果您避开MIN / MAX,您可以根据需要获得任意Nth值:
with q as (
select sal, dr from (
select distinct
sal
,DENSE_RANK() OVER (ORDER BY sal DESC) dr
from emp
) where dr in (1,2,10)
)
select (select sal from q where dr = 1) first
,(select sal from q where dr = 2) second
,(select sal from q where dr = 10) tenth
from dual;
查询(q)应该具体化,因此它的多个查询不应导致额外的数据传递。