Click here to Skip to main content
15,884,960 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
if i have a given employee table
empno	ename	Sal
1		A		7000
2		B		30000
3		C		2000
4		D		10000
5		e		500


Now i want to display 1st highest sal then minimum sal then 2nd max sal then 2nd min sal,ect.... upto ‘n’ records
Output format
empno	ename	Sal
2		b		30000
5		E		500
4		D		10000
3		C		2000
1		A		7000
Posted
Updated 10-Sep-15 9:34am
v2
Comments
barneyman 10-Sep-15 8:31am    
have a look at cursors

1 solution

I understand that this is SQL Oracle question.
But I have not touched Oracle in more than a decade, so here is a way of doing it in tsql :)

Hopefully you should be able to convert to be useful in Oracle.
SQL
with employee  as (
--setup dummy data
	select 
		1 empno,
		'A' ename,
		7000 sal
	union all select 2, 'B', 30000
	union all select 3, 'C', 2000
	union all select 4, 'D', 10000
	union all select 5, 'E', 500
)
select * 
from 
	(select
		row_number() over (order by sal desc) rowid,
		0 Sort,
		count(empno) over () cnt,
		*
		from employee 
	union all
	select
		row_number() over (order by sal asc) rowid,
		1 Sort,
		count(empno) over () cnt,
		*
		from employee) employeeHiLo
where rowid <= (floor(cnt/2) + cnt%2)
order by rowid, sort
 ;

I believe there is an row_number() equivalent in Oracle, so the conversion should be possible.
The cnt column is a bit of a dirty way to figure out how many records to return.

When the sal values are the same, then you may have to add an additional ordering.
Also when an odd number of records are present the high and the low will be the same record, you get an additional row/record. If this is not what you want then fiddle with where clause for odd number of records.

Hope that helps out.

--------------------------------------------------
If you are interested, here is my first attempt.
Gets the hi and lo records in one record.
SQL
with employee  as (
--setup dummy data
	select 
		1 empno,
		'A' ename,
		7000 sal
	union all select 2, 'B', 30000
	union all select 3, 'C', 2000
	union all select 4, 'D', 10000
	union all select 5, 'E', 500
), employeeHiLo  as (
	select
	row_number() over (order by sal desc) hilo,
	row_number() over (order by sal asc) lohi,
	count(empno) over () cnt,
	*
	from employee
)
select 
	*
from employeeHiLo employeeHi
inner join employeeHiLo employeeLo
	on employeeHi.hilo = employeeLo.lohi
where employeeHi.hilo <= (floor(employeeHi.cnt/2) + employeeHi.cnt%2)
;
 
Share this answer
 
Comments
Maciej Los 10-Sep-15 15:35pm    
+5!
jaket-cp 11-Sep-15 4:14am    
thanks :)
aarif moh shaikh 11-Sep-15 1:23am    
Good one +5
jaket-cp 11-Sep-15 4:14am    
:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900