2010-11-23 99 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;