Forums.Sureshkumar.net : A Perfect Place to Share Knowledge         Blogs     Games    Magazines

"Sharing knowledge does not lessen your store, often it gets you more. Sharing plays a key role in relationships and bonding, happens in small steps and is assisted through community membership."

Go Back   SURESHKUMAR.NET FORUMS > Blogs > Elite world
Register FAQ Members List Calendar Games Blogs Search Today's Posts Mark Forums Read

   

In this blog I will post all FAQs, code snippets, real time problems and solutions and any other links which I feel every one needs and can take advantage of.
Rate this Entry

SQL to select middle record of a table

Posted 13-11-07 at 10:48 PM by sk_kireeti
A decision has to taken carefully before we implement a solution for the two possibilities -
  1. When we have odd total number of rows
  2. When we have even total number of rows
My SQL will work differently in each case.

In first case (odd number of total rows), this SQL query will return middle record with out any conflict. Eg., If we have 9 records, this will display 5th record from table.

In second case (even number of total rows), this SQL query will return middle two records as we can't find single middle record. Eg., if we have 14 records in table, it will display both 7th and 8th rows.

select * from
(select rownum sno, empno,ename from emp)
where
sno in
(
select floor((count(*)+1)/2) eg from emp
union
select ceil((count(*)+1)/2) eg from emp
);


output -
--------------------------------------------------
SQL> select count(*) from emp;

COUNT(*)
----------
14

SQL> select * from
2 (select rownum sno, empno,ename from emp)
3 where
4 sno in
5 (
6 select floor((count(*)+1)/2) eg from emp
7 union
8 select ceil((count(*)+1)/2) eg from emp
9 );

SNO EMPNO ENAME
---------- ---------- ----------
7 7782 CLARK
8 7788 SCOTT

SQL> insert into emp(empno) values (20);

1 row created.

SQL> select count(*) from emp;

COUNT(*)
----------
15

SQL> select * from
2 (select rownum sno, empno,ename from emp)
3 where
4 sno in
5 (
6 select floor((count(*)+1)/2) eg from emp
7 union
8 select ceil((count(*)+1)/2) eg from emp
9 );

SNO EMPNO ENAME
---------- ---------- ----------
8 7782 CLARK

SQL>
Posted in Oracle SQL
Comments 1 Email Blog Entry
Total Comments 1

Comments

Old
then can you tell me how do we split the rows in the table into haft if it is odd......
Posted 03-03-08 at 10:06 PM by nithi_papu nithi_papu is offline
Post a Comment Post a Comment
Recent Blog Entries by sk_kireeti

All times are GMT +6.5. The time now is 05:21 AM.





Search Engine Optimization by vBSEO 3.1.0