2010-11-23 41 views
0
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

欢迎...击中CTRL-K后,选择你的代码来正确缩进它。 – Benoit 2010-11-23 12:36:36

+0

@Benoit --- thanx – bunty 2010-11-23 12:39:40

回答

1

另一种方法是使用DENSE_RANK函数;另外,如果你避免MIN/MAX,你可以得到任意的第N值要求:

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)应化所以它的多个查询不应导致通过额外的数据传递。

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;