If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > ANSI SQL > two highest and three lowest salaries (was "Query")

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 02-28-05, 02:28
sashish4529 sashish4529 is offline
Registered User
 
Join Date: Feb 2005
Posts: 29
two highest and three lowest salaries (was "Query")

Hi,

I need to construct a query for table "emp" where in it is possible to pick the two people drawing the highest salary in desc order and botom 3 people drawing lowest salary in ascending order in one result set.

The query
select *
from
( select empno,ename,sal
from emp
order by sal asc )
where rownum < 3

will give me top 2 people

and the query
select *
from
(select empno,ename,sal
from emp
order by sal desc )
where rownum < 4

will give me bottom 3 people.

However when I use
select *
from
( select empno,ename,sal
from emp
order by sal asc )
where rownum < 3
union
select *
from
(select empno,ename,sal
from emp
order by sal desc )
where rownum < 4

the results are jumbled.

Any way out ?

Many Thanks.
Ash
Reply With Quote
  #2 (permalink)  
Old 02-28-05, 08:22
Littlefoot Littlefoot is offline
Lost Boy
 
Join Date: Jan 2004
Location: Croatia, Europe
Posts: 3,629
This is just an idea ... see if it (or its variations) might help you:
Code:
SELECT   empno, ename, sal
    FROM (SELECT   empno, ename, sal
              FROM EMP
          ORDER BY sal ASC)
   WHERE ROWNUM < 3
UNION
SELECT   empno, ename, sal
    FROM (SELECT   empno, ename, sal
              FROM EMP
          ORDER BY sal DESC)
   WHERE ROWNUM < 4
ORDER BY sal;

Last edited by Littlefoot; 02-28-05 at 08:25.
Reply With Quote
  #3 (permalink)  
Old 02-28-05, 08:30
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,524
ash, this is the sql forum

if you want oracle, please post in the oracle forum

let's have standard sql solutions, please
Code:
select X.eno
     , X.ename
     , X.sal
  from emp X
left outer
  join emp Y
    on Y.sal > X.sal
group 
    by X.eno
     , X.ename
     , X.sal
having count(*) < 2
union all
select X.eno
     , X.ename
     , X.sal
  from emp X
left outer
  join emp Y
    on Y.sal < X.sal
group 
    by X.eno
     , X.ename
     , X.sal
having count(*) < 3
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On