First n rows
Version: Oracle 10
How can I get first 'n' rows in a select query but after applying order by;
For eg:
--Get first 4 rows?
select * from abc order by a;
As I understand rownum could be used in "where" clause which means it happens before order by is applied.
I have some examples for emp for top-N and bottom-N Queries
(just in case you want to extend you sql)
TABLE employees
Name Null? Type
EMPLOYEE_ID NOT NULL NUMBER(6)
FIRST_NAME VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(25)
EMAIL NOT NULL VARCHAR2(25)
PHONE_NUMBER VARCHAR2(20)
HIRE_DATE NOT NULL DATE
JOB_ID NOT NULL VARCHAR2(10)
SALARY NUMBER(8,2)
COMMISSION_PCT NUMBER(2,2)
MANAGER_ID NUMBER(6)
DEPARTMENT_ID NUMBER(4)
Task:
Display top two salaries in each department.
1. Using function ROW_NUMBER ():
SELECT employee_id, department_id, salary
FROM (SELECT employee_id, department_id, salary,
ROW_NUMBER () OVER (PARTITION BY department_id ORDER BY salary DESC)
r_no
FROM employees)
WHERE r_no <= 2
EMPLOYEE_ID DEPARTMENT_ID SALARY
200 10 4400
201 20 13000
202 20 6000
114 30 11000
115 30 3100
203 40 6500
100 90 24000
101 90 17000
2. Using function RANK()
SELECT employee_id, department_id, salary, rn
FROM (SELECT employee_id, department_id, salary,
RANK () OVER (PARTITION BY department_id ORDER BY salary DESC)
rn
FROM employees)
WHERE rn <= 2
EMPLOYEE_ID DEPARTMENT_ID SALARY RN
200 10 4400 1
201 20 13000 1
202 20 6000 2
114 30 11000 1
115 30 3100 2
203 40 6500 1
100 90 24000 1
101 90 17000 2
102 90 17000 2
The salaries that are equal (department 90) receive the same rank
Similar Messages
-
When using private browsing to view image results in Safari 5.1.3, only the first two rows of results are visible, the following four or so rows display greyed out place holders, the remainder of the results page is blank, and the safe search button is inoperable. When I turn off private browsing and refresh the page, everything works again.
Anyone else having this problem?I have got the same behaviour after the last Safari Update to 5.1.3. It seems that Safari now handles some scripts in a new way. If you debug the Google Website, you will see, that there is some Javascript Error, that seems to prevent to write into local cache. After some searching I wasn't able to finde a solution for this problem, other then disabling Javascript while private browsing to prevent the script loading. You then are able to use Google with the old layout. The option to disable JavaScript can be found in the Menu "Developer", wich has to be enabled in Safari in the options first.
In my opinion this is a bug that is now occuring, because Apple changed something in private browsing and that has to be fixed by Google now, to run again. Or we will have to wait for 5.1.4, as you can read online Apple will change and bugfix the javascript engine in that version, perhaps this fixes the problem as well. I hope so!
If anyone is in the developer program perhaps you could test this with the beta of 5.1.4 and tell us if it works. -
Af:commandButton only works for the first 10 rows returned in the af:table
Using JDeveloper 10.1.3.2.0.
I am new to ADF programming. I have attempted to create an ADF page that contains a search and return table in the same page. The search appears to work fine but the return table displays odd behavior. If the search returns more than 10 rows such that it is possible to page forward through the rows returned the command button associated with the return table that allows the user to pick a particular row and navigate to another page does not work. If the user finds what he/she is looking for in the first ten rows then the command button works fine and the user is taken to the next page. The command button is actually defined to have an af:setActionListener to set a value in a backing bean and then command button has an action to invoke a backing bean. Both of these fire just fine if the selection is made from the first 10 rows. However once the user pages forward to another set of rows then neither seem to happen. Any advice on where to figure out what I did wrong?When I get a component that seems to do nothing under certain circumstances, the first thing I usually check for is Javascript errors. Sometimes errors on page load can keep a component's Javascript from firing properly.
Try reproducing your problem in Firefox (or another browser with a decent Javascript error console; IE doesn't have one, although I think you can get extensions that provide JS debugging). Check the error console:
# Before scrolling off the first 10 rows.
# Right after scrolling off the first 10 rows.
# After unsuccessfully clicking the command button.
Do any interesting errors show up in steps 2 or 3? -
How can I find out the first intial row in VA02-output transaction??
How can I find out the first intial row in the screen which appears during sales order change (VA02) >>enter the sales order number >>after the first screen appears >>in the menu bar go to EXTRAS>>OUTPUT>>HEADER>>EDIT??
I have to find out the first row in the OUTPUT column which is empty,then populate it with some data using BDC.
usefull answers will be rewarded.
regards,
Shashank .Pass the sale order number in the object key of NAST table,
if u get 3 entires, then u need to place ur entry in the fourth row in that table control thru BDC.
I think u got the logic.
Regards,
Sujatha. -
First visible row on a CatalogTable
My first visible row property on a CatalogTable is always display at row 2. I've set the property to 1 in the layout design and I've tried setting it using within the wdDoModifyView, but it still displays row 2 first. This causes my users to perform a page up to see row 1. Can anyone tell me why I cannot set it correctly?
IWDTable tv = (IWDTable)view.getElement("CatalogTable");
tv.setFirstVisibleRow(1);Hi Steve
IWDTable tv = (IWDTable)view.getElement("CatalogTable");
tv.setFirstVisibleRow(<b>0</b>);
BR
Sergei -
Regarding ssis - skip first 10 rows in excel source
Hi,
I have received an Excel Source file, but the first 10 rows have only company information; actual data starts from Row 11. How will you skip the first 10 rows and start reading from row 11Hi Koteswararao,
If the first row includes the column names, and the first 10 rows you said don’t include the first row. That means you want to skip the rows from 2 row to 10 row, then we can union two Excel sources to work around this issue. For more details, please refer
to the following steps:
Set the FirstRowHasColumnName property of the Excel Connection Manager to False, so the first row stores the column names in the sheet.
Drag two Excel Sources to the Data Flow Task.
In the Excel Source, use the SQL command below to replace the former(supposing there are three columns in the Excel sheet: col1, col2 and col3):
SELECT F1 AS col1,F2 AS col2, F3 AS col3 FROM
[sheet$A1:C1]
In the Excel Source 1, please type the SQL command below (note that the ‘n’ means the number of rows in the sheet):
SELECT F1 AS col1,F2 AS col2, F3 AS col3 FROM
[sheet$A11:Cn]
Drag a Union All component to the same task, then union those two Excel Sources.
If there are any other questions, please feel free to ask.
Thanks,
Katherine Xiong
Katherine Xiong
TechNet Community Support -
Hi Experts ,
I am working on SSIS 2008.
I have Excel file as a Source .
Scenario: First 5 Rows contain some Headings which I dont need
My Actual Header Starts from 6th Row and then Data .
How should I used my Excel source to Take 6th Row as Header and Then Data .
NOTE ::
I receive file every Month .
Name of File is same Every Month
Number and Name of Coumns are Fix
Number of Records are not Fix every month
I tried using OpenRowset in Excel sourcei.e Revenue$A6:D6
A6 =MY FIRST COLUMN HEADER
D6= My LAST COULMN HEADER
Package Executed but No data Loaded in Destination SQL Table
Any Help ??Hi Rihan
I tried using OpenRowset in Excel sourcei.e Revenue$A6:D6
A6 =MY FIRST COLUMN HEADER
D6= My LAST COULMN HEADER
here change the d6 to d(total rows in excel sheet) i.e if if u have 100 rows (A5:D100)
Regards
bhimireddy -
Setting first visible row in Web Dynpro ALV in Releases above 7.0
Hello Everybody,
I have an ALV in which a particular row should be set to lead selection and also set as the first visible row in this ALV for the first display. The index for this row is determined at runtime.
I used the method SET_FIRST_VISIBLE_ROW of the interface IF_SALV_WD_TABLE_SETTINGS and it worked fine in a system of Release 7.0.
However, after the system has been upgraded to 7.02, this is not working. The row is lead selected but it is not set as the first visible row and as a result I need to scroll down and look for the row that is lead selected.
Does anybody have suggestions?
Thanks!
VidyaHello Srilatha,
Thanks a lot for your suggestion! I am calling method SET_FIRST_VISIBLE_ROW in the wddoinit method of the view.
I tried checking in the debugging mode by inserting a call to GET_FIRST_VISIBLE_ROW in both the wddoinit method as well as wddomodifyview method.
The value of the first visible row is correct in both these methods but when the screen is rendered, the first row of the ALV continues to be the first visible row.
CALL METHOD wd_this->lref_nd_node_rename->set_lead_selection_index
EXPORTING
index = lv_leadselection.
wd_this->lref_table_settings ?= wd_this->lref_value.
CALL METHOD wd_this->lref_table_settings->set_first_visible_row
EXPORTING
value = lv_leadselection.
" Set vertical scrollbar height to 15 rows
CALL METHOD wd_this->lref_table_settings->set_visible_row_count
EXPORTING
value = '15'.
Here lv_leadselection contains the index of the row that needs to be lead selected (in this case it is 3)
lref_value is of type CL_SALV_WD_CONFIG_TABLE
lref_table_settings is of type IF_SALV_WD_TABLE_SETTINGS
lref_value and lref_table_setings are view attributes.
Thanks and best regards,
Vidya -
Regarding ssis - Filter first 5 rows from flat file
Hi,
i have a requirement like this every day we receive 10-15 Flat files , we need to load these data into SQL Table ,here nothing is complex for this we need to use foreachloop Container,Dataflowtask..etc. here the issue is each flat file have top 5 rows has
Client information like ( We need to delete First 5 rows) and then insert into SQL Table . please suggest me how to develope the package..You need to use a script task to read file one by one and remove the first 5 rows from the file. The file name/path can be stored as a variable and read it from the script code. Insert the script task inside the foreach loop container just before importing
the file.
Refer the link to remove a line in .net
http://stackoverflow.com/questions/7008542/removing-the-first-line-of-a-text-file-in-c-sharp
Regards, RSingh -
Selecting first 15 rows and displaying next 15
I wish to select the first 15 rows from my database and then have an option select a next page, whereby the next 15 rows are displayed. I'm not sure how to go about it, could someone enlighten me. For reference, it would be something like how the forums is done, whereby they display x amount of threads, and you would have to go to the next page.
This can be done by retrieving the first 15 using something like rownum <= 15 in the where clause.
Then, by remembering the ID of the last thread that was displayed you select threads id > lastID and rownum <= 15... that is the first 15 rows that match your query starting immediately after the last thread searched.
It's not unusual to retrieve and store a list of the Thread IDs completely as this allows a more stable feedback at the expense of heavier session information being stored.
Hope that helps
Talden -
Want to fetch first two row from database
i'm having a database with multiple rows. I want to fetch first two rows form it dynamically, what should i have to do???.plz help....
the data comes from external source and updating the database, at the same time i've to read only first two rows, plz explain.
-
HI EXPORTS,
MY QURY IS
SELECT TOT.HTNO, TOT.RESULT_NAME, TOT.TOTALMARKS, TOT.TOTALRANK,
TOT.RESEXAMSLNO, TOT.RESACADEMICSLNO, TOT.RESGROUPSLNO,
TOT.RESCORPCOLLSLNO, TOT.DISTRICTSLNO
FROM RESULT_STUDENTMARKS_TOTALS TOT
WHERE TOT.RESEXAMSLNO = 1
AND TOT.RESGROUPSLNO = 1
AND TOT.RESACADEMICSLNO = 9
AND TOT.RESCORPCOLLSLNO IN (99)
AND TOT.DISTRICTSLNO IN (4)
AND ROWNUM <5
ORDER BY TOT.HTNO
I WANT FIRST 4 ROWS OF DATA BASED ON ASSENDING ORDER CAN U CHAGE IS QURY OR
GIVEN ANY EXAMPLE OF FIRST 4 ROWS OF DATA ORDER BY ONLY ONE FIELD IN THAT TABLE
THANX & REGARDS
ASHOK
Edited by: Ashok on Apr 28, 2011 11:01 PMSee
http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:62364503028143
and
http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:2853107469873
You have to filter the ROWNUM after the ORDER BY.
so :
select * from
SELECT TOT.HTNO, TOT.RESULT_NAME, TOT.TOTALMARKS, TOT.TOTALRANK,
TOT.RESEXAMSLNO, TOT.RESACADEMICSLNO, TOT.RESGROUPSLNO,
TOT.RESCORPCOLLSLNO, TOT.DISTRICTSLNO
FROM RESULT_STUDENTMARKS_TOTALS TOT
WHERE TOT.RESEXAMSLNO = 1
AND TOT.RESGROUPSLNO = 1
AND TOT.RESACADEMICSLNO = 9
AND TOT.RESCORPCOLLSLNO IN (99)
AND TOT.DISTRICTSLNO IN (4)
ORDER BY TOT.HTNO
where rownum < 6
order by 1Hemant K Chitale
Edited by: Hemant K Chitale on Apr 29, 2011 2:28 PM
Changed "rownum < 5" to "rownum < 6" to get 5 rows. -
Selecting the first n rows with Oracle
Please help,I am very confused with this.
For example,lets take a table called "items" which has
ID NAME PRICE
1 cup 1.2
2 book 49.99
3 mobile 89.99
20 bike 1250
19 egg 0.8
18 bun 2.5
17 color 2.22
16 tv 310
15 air 0
14 laptop 999.5
13 pack 21.53
12 cd/r 1.2
11 table 198
10 apple 1.05
9 carpet 122.4
8 oracle 19999
7 door 150
6 dollar 1
5 pencil 1.35
Next,say, we want to retrieve the five cheapest items.
select name, price
from items
where rownum < 6
order by price;
NAME PRICE
coke .78
cup 1.2
pencil 1.35
book 49.99
mobile 89.99
This is wrong. In the result set above, the item with id no 19 (egg) is missing which only costs 0.80 (currency units). We get this because
Oracle first retrieves the first five rows and then orders them by price. This is because of the fact that we didn't explicitly enough state what we meant with first.
This problem can be solved by using row_number with a option--->below
select name, price
from (
_*select name, price, row_number() over (order by price) r*_
_*from items*_
where r between 1 and 5;
NAME PRICE
air 0
coke .78
egg .8
dollar 1
apple 1.05
**Question is in the above select if i ADD the clause "WHERE rownum <= 6"---The above result set goes wrong again.I dont get the correct order as above.
Please help.Can we have the order by done first and then take 5 records of them.
select name, price
from (
select name, price, row_number() over (order by price) r
*from items WHERE rownum <= 6*
where r between 1 and 5wrote:user_7000011
Thanks.
*But, what i wanted is in the inner most select where we select from item --I need to add a where qualification as below.*
select * from
(select name, price, dense_rank() over (ORDER by price desc ) rank from item where rownum <=6
) a
where a.rank<6
Well, the rank limitation is having the same effect in that query, so there's no need to try and put "rownum <=6" in that case.What you need to understand is that "rownum" is a pseudo column that is generated when the results of a query are already determined, but it is applied before any ordering takes place (as the where clause is evaluated before the order by clause).
So if you try and say "where rownum <= 6 order by x", you are under the misunderstanding that it will order the data first and then take the first 6 rows. This isn't the case. It will take the first 6 rows (whatever they may be) and then order those.
In order to order first and then take 6 rows you have to order your data without restriction and then wrap that in a query to restrict it.
Hence...
select x
from tableX
where rownum <= 6
order by xbecomes
select x
from (select x
from tableX
order by x)
where rownum <= 6This ensures that the data is selected and ordered first and then the first 6 rows are taken from that. -
Delete first empty row in a table
Hi,
Can you please provide the script for the below requirement.
Need to delete First empty row in all the tables. (Tables having more number of empty rows. i need to delete first empty row only)
Regards,
Velu@Velu – the following blog post by Jongware might get you started:
Tackling Tables through Scripting
by: Jongware | April 8, 2013
http://indesignsecrets.com/tackling-tables-through-scripting.php
Document Object (DOM) documentation:
Indesign JavaScript Help
InDesign ExtendScript API (10.0)
Table Row specifics:
Adobe InDesign CS6 (8.0) Object Model JS: Row
InDesign ExtendScript API (10.0)
Uwe -
Hi Experts,
In an interface i'm uploading a spread sheet data into the program's internal table. I dont want the first 2 rows of the spreadsheet in the internal table as they are just the headings.
plz advise me.
thank you.
venudata: begin of itab occurs 0,
name1 type c,
name2 type c,
end of itab.
data: t_filedata like alsmex_tabline occurs 0 with header line.
start-of-selection.
clear itab.
refresh itab.
*---Upload Spreadsheet.
perform read_file using p_xlfile.
*---Process data into formatted internal table.
perform format_data.
form read_file using p_filename like rlgrap-filename.
*---Upload spreadsheet.
CALL FUNCTION 'ALSM_EXCEL_TO_INTERNAL_TABLE'
EXPORTING
FILENAME = p_filename
I_BEGIN_COL = 1
I_BEGIN_ROW = 1
I_END_COL = 256
I_END_ROW = 65536
TABLES
INTERN = t_filedata
EXCEPTIONS
INCONSISTENT_PARAMETERS = 1
UPLOAD_OLE = 2
OTHERS = 3
IF t_filedata[] is initial.
message i009 with 'NO DATA FOUND IN FILE' p_filename.
stop.
ENDIF.
sort t_filedata by row col.
endform. "READ_FILE
form format_data.
data: l_index type i.
field-symbols: <fs1>.
loop at t_filedata.
can i write that like this, here?????????
1method:
<b>delete t_filedata index 1.
delete t_filedata index 2.</b>
2nd method:
or
<b>check sy-tabix > 2.</b>
l_index = t_filedata-col.
assign component l_index of structure t_sheet to <fs1>.
<fs1> = t_filedata-value.
at end of row.
append itab.
clear itab.
endat.
endloop.
refresh t_filedata.
free t_filedata.
endform. "FORMAT_DATA
Message was edited by: venu gopal -
I know the FIRST_ROWS hint tells the optimizer to minimize time to first row. I know the new 12c functionality for "FETCH [FIRST|NEXT] [N] ROWS [ONLY|WITH TIES]"fetch first/next N rows only/with ties" will implement the query using ROW_NUMBER(). Should I leave hint in case it improves performance, or does the FETCH FIRST clause make this hint redundant?
maybe the answer to this question is more complicated then I assumed at first: as Randolf Geist wrote in his presentation Everything You Wanted To Know About FIRST_ROWS_n But Were Afraid To Ask a rownum predicate implicitly defines a first rows n optimization. So I guessed that the fetch first clause would trigger a similar optimization. But a rownum predicate and a fetch first clause are not transformed into the same operation:
create table t
as
select rownum id
from dual
connect by level <= 1000000;
select id
from t
where rownum <= 5;
ID
1
2
3
4
5
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 5 | 25 | 2 (0)| 00:00:01 |
|* 1 | COUNT STOPKEY | | | | | |
| 2 | TABLE ACCESS FULL| T | 5 | 25 | 2 (0)| 00:00:01 |
Predicate Information (identified by operation id):
1 - filter(ROWNUM<=5)
select id
from t
fetch first 5 rows only;
ID
1
2
3
4
5
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1000K| 24M| 427 (1)| 00:00:01 |
|* 1 | VIEW | | 1000K| 24M| 427 (1)| 00:00:01 |
|* 2 | WINDOW NOSORT STOPKEY| | 1000K| 4882K| 427 (1)| 00:00:01 |
| 3 | TABLE ACCESS FULL | T | 1000K| 4882K| 427 (1)| 00:00:01 |
Predicate Information (identified by operation id):
1 - filter("from$_subquery$_002"."rowlimit_$$_rownumber"<=5)
2 - filter(ROW_NUMBER() OVER ( ORDER BY NULL )<=5)
Looking at a CBO trace for the two operations I see signs of a first rows optimization only for the query with the rownum predicate:
Final query after transformations:******* UNPARSED QUERY IS *******
SELECT "T"."ID" "ID" FROM "C##TEST"."T" "T" WHERE ROWNUM<=5
First K Rows: Setup begin
And so I think there is no first rows optimization for the fetch first clause. Of course the analytics would make an optimization for fast response almost impossible if there is an order in the query since in this case the analytics have to read the complete set before the filtering takes place.
Regards
Martin Preiss
Maybe you are looking for
-
Web help is not working in ie11
Hi, I have asp.net application and a adobe robo help 7.I have the WebHelp folder after generate ouput. if run the help help in ie11.. am geeting error at xmldoc.load(). But the same is working in other browser, such as ie 8 and firefox. Thanks & Reg
-
hi, in case of make to stock/project sales etc -a/c determination will happen based on KOFK ctype for which posting will happen to FI & CO i want to know what value exactly gets posted to controlling Pl suggest
-
I am a Windows Vista User. I updated my iTunes Version 10.3. Then, when I re-opened my iTunes, all files were gone! Good thing I consolidated the files and just imported the files again. But, this happens every time I close and open my iTunes. Help?
-
My Dad who is 81 is finding his iphone difficult to use. At first I was surprised that he struggles to use it. He had no problems using his old style cell phone. But after trying to teach him how to use the iphone I can now see why he struggles with
-
VL10C and E having problem in Background run
Hi, When i Try using VL10C, VL10E in Background mode i am not able to create any delivery and where as Foreground I can able to create with specific customer and material. Please suggest if you come across same senario in ECC 6 version. Prog backgrou