简体   繁体   中英

How can I print the first three rows and the last three rows one under another in ORACLE SQL?

In ORACLE SQL, I want to print the first two and the last two rows one under the other. How can I do this with a one query? Suppose you have table with ten rows. I want to print the first two rows and the last two rows as below:

Row Number Values
1 A
2 B
9 C
10 D

You can use row_number()over(order by row_number) window function to achieve what you are looking for. Even you can have first two rows order by row_number and last two rows order by column valuess if you want (row_number()over(order by row_number)FirstRowNumber, row_number()over(order by valuess desc)LastRowNumber )).

Table structure and insert statement:

create table tableName (Row_Number int, Valuess varchar(20));
insert into tablename values(1,'A');
insert into tablename values(2,'B');
insert into tablename values(9,'C');
insert into tablename values(10,'D');
insert into tablename values(11,'E');
insert into tablename values(12,'F');

Query:

SELECT ROW_NUMBER,Valuess FROM (
select ROW_NUMBER,Valuess,row_number()over(order by row_number)FirstRowNumber, row_number()over(order by row_number desc)LastRowNumber from tablename ) T
WHERE FIRSTROWNUMBER<=2 OR LASTROWNUMBER<=2
ORDER BY FIRSTROWNUMBER

Output:

ROW_NUMBER VALUESS
1 A
2 B
11 E
12 F

I think you need below query,

select t.*
from (select table1.*, row_number() over (order by [Row Number]) as seqnum,
             count(*) over () as cnt
      from table1
     ) t
where seqnum in( 1,2) or seqnum in( cnt, cnt-1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM