Query for last  n rows please

Hi All,
Can anybody give me a SQL Query which will select last n rows from a table.
guess some time I see this query in this forum but forgot to note it down.
Thanks in Advance
[email protected]

Hi All,
There is a simple solution, which will be useful at some of the following cases.
1) Find Top( or bottom) <n> rows.
For e.g. Top 5 rows or Bottom 100 rows.
2) Range of rows.
For e.g. Row 11 to row 20. (which is required for displaying the dynamic pages on web search engines)
We need to understand how Oracle processes the query.
SQL>Select rownum, Ename, Sal from Emp;
ROWNUM ENAME SAL
1 A 1000
2 B 800
3 C 3500
But, if we write the query in following manner, check the output to understand Oracle's query processing.
SQL>Select rownum, Ename, Sal from Emp order by Sal;
ROWNUM ENAME SAL
2 B 800
1 A 1000
3 C 3500
The above output makes it clear that the rownum is assigned to the array of output before sorting it.
Therefore, if you have to use the rownum of sorted output, you will have to use the inline query.
SQL>Select rownum, Ename, Sal from (Select Ename, Sal from Emp ) order by Sal;
ROWNUM ENAME SAL
1 B 800
2 A 1000
3 C 3500
The above query can be used, but not for any kind of filter conditions. Please check the tricky part of this filter condition.
SQL>Select rownum, Ename, Sal from (Select Ename, Sal from Emp ) order by Sal
where rownum = 2;
No rows returned.
This is because the rownums are generated first, then the filter is applied for Each row.
Therefore, if the rownum is 1 it is filtered out. Therefore, the second row becomes first row( rownum = 1) and again it gets filtered out.
Therefore, here we need to use one more inline query.
SQL>Select rnum, Ename, Sal from (
Select rownum rnum, Ename, Sal from (Select Ename, Sal from Emp ) order by Sal)
where rnum = 2;
ROWNUM ENAME SAL
2 A 1000
Think, with this above discussion, you can generate any type of query.
Regards.
Yogesh D.

Similar Messages

  • Query for last four rows?

    please write query for get the last four rows from a table

    ratnakar wrote:
    please write query for get the last four rows from a tablelast 4 rows is indeterminate.
    rows in a table are like balls in a basket.
    which are last 4 balls in any basket?
    Handle:     ratnakar
    Email:     [email protected]
    Status Level:     Newbie
    Registered:     Aug 27, 2012
    Total Posts:     34
    Total Questions:     16 (11 unresolved)
    why so MANY unanswered questions?

  • I must find my find my iphone data for last 1 year please help me

    i must find my find my iphone data for last 1 year please help me

    I confirmed, I have turned on " find my iphone. Here is the error I encountered

  • Query for last 8 days results

    any body have a query for last 8 days results
    TIMESTAMPADD(SQL_TSI_DAY, -8, CURRENT_DATE) this is resulting only 1 day results only .if i execute this query is it displaying 8th back day results only.
    i want all 8 back days results .
    anybody have query for this...
    Edited by: user12255470 on Apr 28, 2010 7:19 AM

    This works fine for me:
    SELECT "D0 Time"."T00 Calendar Date" saw_0, "F1 Revenue"."1-01 Revenue (Sum All)" saw_1 FROM "Sample Sales" WHERE "D0 Time"."T00 Calendar Date" BETWEEN TIMESTAMPADD(SQL_TSI_DAY, -8, CURRENT_DATE) AND TIMESTAMPADD(SQL_TSI_DAY, -1, CURRENT_DATE) ORDER BY saw_0
    regards
    John
    http://www.obiee101.blogspot.com/

  • How to find top utilized query for last two months in oem

    how to find top utilized query for last two months in oracle enterprise manager?

    Can you mark the thread as Helpful  and once marked the information can be reviewed by other customer for similar queries
    Regards
    Krishnan

  • If there is no data for a specific row, please don't show the row at all.

    Hi,
    If there is no data for a specific row, please don't show the row at all.
    how can this be done??
    Thanks in advance.

    Not clear no data for row?
    Did you try with Pivot table? that should take care of it.
    Let us know updates

  • Query for last 5 Purchase Price for items

    Dear All
    I was trying to write a query in which
    i want to display Items with last 5 purchase price
    itemcode     UOM      Last Purchase Price        II Last Pur Price       III Last Pur Price        IV Last Pur Price         V Last Pur Price
    but not getting right result because of future posting and post date entries as I am considering Max(DocNum) for Query.
    SELECT distinct a.ItemCode, a.invntryUom
    , (select Price from PCH1 where itemcode=a.itemcode and
    docentry=(select max(docentry) from PCH1 where itemcode=a.ItemCode)) as 'II Pur. Price'
    , (select Price from PCH1 where itemcode=a.itemcode and
    docentry=(select max(docentry) from PCH1 where itemcode=a.ItemCode and docentry<(select max(docentry) from PCH1 where itemcode=a.ItemCode))) as 'II Pur. Price'
    , (select Price from PCH1 where itemcode=a.itemcode and
    docentry=(select max(docentry) from PCH1 where itemcode=a.ItemCode and docentry<(select max(docentry) from PCH1 where itemcode=a.ItemCode and docentry<(select max(docentry) from PCH1 where itemcode=a.ItemCode)))) as 'III Pur. Price'
    , (select Price from PCH1 where itemcode=a.itemcode and
    docentry=(select max(docentry) from PCH1 where itemcode=a.ItemCode and docentry<(select max(docentry) from PCH1 where itemcode=a.ItemCode and docentry<(select max(docentry) from PCH1 where itemcode=a.ItemCode and docentry<(select max(docentry) from PCH1 where itemcode=a.ItemCode))))) as 'IV Pur. Price'
    , (select Price from PCH1 where itemcode=a.itemcode and
    docentry=(select max(docentry) from PCH1 where itemcode=a.ItemCode and docentry<(select max(docentry) from PCH1 where itemcode=a.ItemCode and docentry<(select max(docentry) from PCH1 where itemcode=a.ItemCode and docentry<(select max(docentry) from PCH1 where itemcode=a.ItemCode and docentry<(select max(docentry) from PCH1 where itemcode=a.ItemCode)))))) as 'V Pur. Price'
    , Max(b.docentry) as 'MaxDocEntry'
    FROM OPCH INNER JOIN
    PCH1 b ON OPCH.DocEntry = b.DocEntry INNER JOIN
    OITM a ON b.ItemCode = a.ItemCode
    group by a.ItemCode, a.invntryUom
    order by a.ItemCode
    Please help me on this.
    Regards
    Anubha Paliwal

    Hi........
    Try this......
    SELECT Top 5 T0.[DocNum], T1.[ItemCode], T1.[Dscription], T1.[Price], T3.[ItmsGrpCod],
    T3.[ItmsGrpNam] FROM OPCH T0 INNER JOIN PCH1 T1 ON T0.DocEntry = T1.DocEntry
    INNER JOIN OITM T2 ON T1.ItemCode = T2.ItemCode INNER JOIN OITB T3 ON
    T2.ItmsGrpCod = T3.ItmsGrpCod WHERE T3.[ItmsGrpNam] ='[%0]' ORDER BY T0.[DocDate] desc
    Regards,
    Rahul

  • VStest.console.exe Query for a Data Row Result DURING Test Execution Status

    I started with the following
    thread and was asked to create a new thread. 
    I have the following test that reads a .csv as a data source.
    /// <summary>
    /// Summary description for Test
    /// </summary>
    [TestCategory("LongTest"),
    TestCategory("Visual Studio 2013"), TestMethod]
    [DeploymentItem("data.csv")]
    [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV",
    "|DataDirectory|\\data.csv",
    "data#csv",
    DataAccessMethod.Sequential),
    DeploymentItem("data.csv")]
    public void Create_And_Build_All_Templates()
    testmethodname = "Create And Build All Templates ";
    LaunchVisualStudio2013();
    When I run the test from VStest.console.exe, I see the following:
    vstest.console.exe /testcasefilter:"TestCategory=LongTest" /settings:"C:\testing\CodedUI.testsettings" /logger:TRX /logger:CodedUITestLogger C:\AppTests\CodedUITest.dll
    Microsoft (R) Test Execution Command Line Tool Version 12.0.31101.0
    Copyright (c) Microsoft Corporation. All rights reserved.
    Running tests in C:\testing\bin\debug\TestResults
    Starting test execution, please wait...
    I want to report on the status of the iterations DURING the test run from VStest.console.exe, like how the test explorer window does this. 
    How can I achieve the output below (notice the (Data Row ) values) ?
    vstest.console.exe
    /testcasefilter:"TestCategory=LongTest"
    /settings:"C:\testing\CodedUI.testsettings"
    /logger:TRX
    /logger:CodedUITestLogger
    C:\AppTests\CodedUITest.dll
    Microsoft (R) Test Execution Command Line Tool Version 12.0.31101.0
    Copyright (c) Microsoft Corporation. All rights reserved.
    Running tests in C:\testing\bin\debug\TestResults
    Starting test execution, please wait...
    Test Passed - Create_And_Build_All_Templates (Data Row 1)
    Test Passed - Create_And_Build_All_Templates (Data Row 2)
    Test Failed - Create_And_Build_All_Templates (Data Row 3)
    Test Passed - Create_And_Build_All_Templates (Data Row 4)
    Ian Ceicys

    Jack, again the results are printed to the std. out console AFTER the test data row has been completed. Is there a way to query VSTest.console and find out which test\data row is being executed so it can be written out to the console
    DURING the test run? 
    I put together the following screencast showing the issue: 
    http://www.screencast.com/t/IrxxfhGlzD
    Also here is the github repo with the source code that I included in the screen cast:
    https://github.com/ianceicys/VisualStudioSamples2015
    Take a look at LongRunningDataDrivenTest.sln
    Unit Test
    [TestClass]
    public class UnitTest
    public static int _executedTests = 0;
    public static int _passedTests = 0;
    public void IncrementTests()
    _executedTests++;
    public void IncrementPassedTests()
    _passedTests++;
    [TestInitialize]
    public void TestInitialize()
    IncrementTests();
    Console.WriteLine("Total tests Row executed: {0}", _executedTests);
    [TestCleanup]
    public void TestCleanup()
    if (TestContext.CurrentTestOutcome == UnitTestOutcome.Passed)
    IncrementPassedTests();
    Console.WriteLine("Total passed tests: {0}", _passedTests);
    private TestContext testContextInstance;
    /// <summary>
    /// Long Running Test
    /// </summary>
    [TestCategory("Long Running Test Example"),TestMethod]
    [DeploymentItem("data.csv")]
    [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV",
    "|DataDirectory|\\data.csv",
    "data#csv",
    DataAccessMethod.Sequential),
    DeploymentItem("data.csv")]
    public void LongRunning_TestMethod_Takes_Over_30_Seconds_to_Run()
    WaitTime(Convert.ToInt32(TestContext.DataRow["WaitTime"].ToString()));
    public void WaitTime (int waittime)
    Thread.Sleep(waittime);
    public TestContext TestContext
    get { return testContextInstance; }
    set { testContextInstance = value; }
    data.csv
    WaitTime,
    13000
    19000
    10000
    11000
    15000
    Ian Ceicys

  • Query for Last Communicated Time

    Hi Folks,
    I've searched the forums and I think it may be out there, but I can't find it. Simply put, I'm looking for a WQL query to list all client systems that have communicated with the SCCM server in the last 1 month (or 30 days).
    I have tried { SMS_R_System.LastLogonTimestamp < DateAdd(dd,-30,GetDate()) }, but it is not accurate.
    The "Last Activity" column/criteria looks promising, but I can't find the code to use it.
    Any help in this matter would be appreciated.
    -Bill

    Why not using the build in report: Clients that have not reported recently (in a specified number of days) 
    More information in the following thread:
    http://social.technet.microsoft.com/Forums/systemcenter/en-US/57d0a157-e7d4-40a7-93c7-24ce152afcb2/looking-for-a-report-for-sccm-client-last-contact?forum=configmgrai
    Please take a moment to Vote as Helpful and/or Mark as Answer where applicable. Thanks.

  • WQL Query for Last Policy Request

    I'm trying to create a collection based on workstations whose last policy request was more than 30 days ago and I'm having trouble with the query statement.  Any help would be greatly appreciated.

    You can query v_CH_ClientSummary to get last policy request and join
    v_r_system in order to get the comuter name.
    That SQL and cannot be used for building a collection ... 
    Torsten Meringer | http://www.mssccmfaq.de

  • Sql query for quarter data..Please help

    Dear Experts,
    Please help with this query...
    i have data like below:
    Year
    Quarter
    MRR
    MRR%
    2012
    Q1
    10
    Q2
    30
    Q3
    50
    Q4
    60
    2013
    Q1
    20
    Q2
    30
    Now i need to caluclate MRR % column values as below
    for 2012 Q2 MRR % = (Q2MRR-Q1MRR)/Q1*100 that is (30-10)/10*100
    for 2012 Q3 MRR % = (Q4MRR-Q3MRR)/Q2*100
    for 2012 Q4 MRR %=  (Q1MRR-Q4MRR)/Q1*100  here q1 of 2013 and q4 of 2012...
    like this it wll go on..
    Please help with me query compute values in MRR % column.
    Best regards
    asp

    Maybe NOT TESTED! No Database at hand
    select year,quarter,mrr,
           ratio_to_report(q_mrr) over (partition by year order by quarter) pct_mrr
      from (select year,quarter,mrr,
                   mrr - lag(mrr,1,0) over (partition by year order by quarter) q_mrr
              from t
    Regards
    Etbin

  • Query for Last page visit by user/session and get version # of current page

    Hi Guru's,
    Any have a query to retrive last page visited by user / session? Somewhere from apex view fir 3.0 or later version? Also looking for query to get version number of current page

    RequestCtx.getResponsibilityId() should return you the Responsibility Id &
    RequestCtx.getUserId() should return the User Id.
    As I understand RequestCtx values are always available in the JSP Page. Kindly check again.

  • How to Query for last updated data in planning Cube?

    Hi,
    i want to see the last updated data with specific timestamp on one of our planning application Cube, IS it possible ?
    I have gone through application log and essbase server log but didn't get much information
    Can any one please let me know.
    Thx

    How was the data updated, if it was through planning then you can enabling data auditing and you should be able to then query the information.
    If it is was a data load then in EAS go the database, edit properties, modications, it should display data load information.
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • FDM Scripting Query for last imported source file using Batch Processing

    Hi Experts,
    I'm currently in the processing of automating the FDM load process on our version of FDM 9.3.3 using batch processing and the FDM Task Manager. Most of the process works fine including an email alert which notifies users of when a data load has taken place.
    As part of that email alert I am trying to attach the source file that has been loaded in batch processing. I have managed to get an attachment using the following FDM Script Object of:
    "API.MaintenanceMgr.fPartLastFile(strLoc, True, False)".
    But have noticed that using this only attaches the last "manually" imported file rather than the last file imported using the batch processing.
    My question is: Is it possible for someone to steer me into the right direction of either a more appropriate API or if I have missed a step in my script.
    Any help as always would be much appreciated.
    Cheers
    Pip

    Unfortunately the batch process does not work the same way as on-line. I am assuming you are using the normal batch load and not Multiload (although the batch is simisar).
    the batch file name gets recorded on the tBatchContents table, and moved to the import/batches folder under the folder for the current batch run. However, if successful the file gets deleted (and from memory does not get archived). To add the import file to the e-mail, after a successful load, i think you will need to store a copy of it prior to importing the file.

  • QUERY FOR HOW TO ACCESS NEXT ROW WHILE IN CURRENT ROW

    Hi, can you please make a oracle sql query for the following.
    My Data in table dt0attlog:
    ID  staffid  logdt          login                        logout       
    01  aw101    01.12.11   01.12.11 08.30   
    01  aw101    01.12.11                             01.12.11 10.30   
    01  aw101    01.12.11   01.12.11 11.40   
    01  aw101    01.12.11                            01.12.11 14.30   
    01  aw101    01.12.11   01.12.11 15.00   
    01  aw101    01.12.11                             01.12.11 17.45   
    01  aw102    01.12.11   01.12.11 19.20   
    01  aw102    01.12.11                               01.12.11 20.30   
    01  aw102    01.12.11   01.12.11 21.50   
    01  aw102    01.12.11                             01.12.11 23.10   
    01  aw102    01.12.11   01.12.11 23.20   
    01  aw102    02.12.11                          02.12.11 07.00   
    01  aw102    02.12.11   02.12.11 18.00
    01  aw102    03.12.11                        03.12.11 04.30
    01  aw103    01.12.11   01.12.11 09.40 
    01  aw104    01.12.11                         01.12.11 18.00   
    My required output:
    ID  staffid      logdt      login                    logout                diff-in-seconds   
    01  aw101    01.12.11   01.12.11 08.30    01.12.11 10.30  7200
    01  aw101    01.12.11   01.12.11 11.40    01.12.11 14.30  10200
    01  aw101    01.12.11   01.12.11 15.00    01.12.11 17.45  9900
    01  aw102    01.12.11   01.12.11 19.20    01.12.11 20.30  4200
    01  aw102    01.12.11   01.12.11 21.50    01.12.11 23.10  4800
    01  aw102    01.12.11   01.12.11 23.20    02.12.11 07.00  27600
    01  aw102    02.12.11    02.12.11 18.00    03.12.11 04.30  37800
    01  aw103    01.12.11   01.12.11 09.40
    01  aw104    01.12.11              01.12.11 18.00
    Here record aw102 & dt. 01.12.11 / 02.12.11, it should shows the next day out in
    the current date ie. 01.12.11.
    thanks and await your great help please.

    the followings are the testcase
    SQL> create table dt0device (
      2     deviceid varchar2(15),
      3     staffid varchar2(10),
      4     logdt  date,
      5      in_out_flag varchar2(3));
    Table created.
    SQL>  insert into dt0device values('01','aw101',to_date('01.12.2011 08:30','DD/MM/RRRR HH24.MI'),'IN');
    1 row created.
    SQL>   insert into dt0device values('01','aw101',to_date('01.12.2011 10:30','DD/MM/RRRR HH24.MI'),'OUT');
    1 row created.
    SQL>   insert into dt0device values('01','aw101',to_date('01.12.2011 11:40','DD/MM/RRRR HH24.MI'),'IN');
    1 row created.
    SQL>   insert into dt0device values('01','aw101',to_date('01.12.2011 14:30','DD/MM/RRRR HH24.MI'),'OUT');
    1 row created.
    SQL>   insert into dt0device values('01','aw101',to_date('01.12.2011 15:00','DD/MM/RRRR HH24.MI'),'IN');
    1 row created.
    SQL>   insert into dt0device values('01','aw101',to_date('01.12.2011 17:45','DD/MM/RRRR HH24.MI'),'OUT');
    1 row created.
    SQL>
    SQL>   insert into dt0device values('01','aw102',to_date('01.12.2011 19:20','DD/MM/RRRR HH24.MI'),'IN');
    1 row created.
    SQL>   insert into dt0device values('01','aw102',to_date('01.12.2011 20:30','DD/MM/RRRR HH24.MI'),'OUT');
    1 row created.
    SQL>   insert into dt0device values('01','aw102',to_date('01.12.2011 21:50','DD/MM/RRRR HH24.MI'),'IN');
    1 row created.
    SQL>   insert into dt0device values('01','aw102',to_date('01.12.2011 23:10','DD/MM/RRRR HH24.MI'),'OUT');
    1 row created.
    SQL>   insert into dt0device values('01','aw102',to_date('01.12.2011 23:20','DD/MM/RRRR HH24.MI'),'IN');
    1 row created.
    SQL>   insert into dt0device values('01','aw102',to_date('02.12.2011 07:00','DD/MM/RRRR HH24.MI'),'OUT');
    1 row created.
    SQL>   insert into dt0device values('01','aw102',to_date('02.12.2011 18:00','DD/MM/RRRR HH24.MI'),'IN');
    1 row created.
    SQL>   insert into dt0device values('01','aw102',to_date('03.12.2011 04:30','DD/MM/RRRR HH24.MI'),'OUT');
    1 row created.
    SQL>
    SQL>   insert into dt0device values('01','aw103',to_date('01.12.2011 09:40','DD/MM/RRRR HH24.MI'),'IN');
    1 row created.
    SQL>   insert into dt0device values('01','aw104',to_date('01.12.2011 18:00','DD/MM/RRRR HH24.MI'),'OUT');
    1 row created.
    SQL>  create table dt0attlogdevice
      2     ( staffid   varchar2(10),
      3       logdt date,
      4       login  date,
      5       logout date);
    Table created.
    SQL>   insert into dt0attlogdevice  select staffid,logdt,
      2              decode(in_out_flag,'IN',logdt,null) login,
      3              decode(in_out_flag,'OUT',logdt,null) logout
      4       from dt0device;
    16 rows created.
    SQL> select staffid,to_char(logdt,'DD/MM/RR') logdt, to_char(login,'DD/MM/RR HH24.MI') login,
      2  to_char(logout,'DD/MM/RR HH24.MI') logout
      3  from dt0attlogdevice;
    STAFFID    LOGDT    LOGIN          LOGOUT                                      
    aw101      01/12/11 01/12/11 08.30                                             
    aw101      01/12/11                01/12/11 10.30                              
    aw101      01/12/11 01/12/11 11.40                                             
    aw101      01/12/11                01/12/11 14.30                              
    aw101      01/12/11 01/12/11 15.00                                             
    aw101      01/12/11                01/12/11 17.45                              
    aw102      01/12/11 01/12/11 19.20                                             
    aw102      01/12/11                01/12/11 20.30                              
    aw102      01/12/11 01/12/11 21.50                                             
    aw102      01/12/11                01/12/11 23.10                              
    aw102      01/12/11 01/12/11 23.20                                             
    STAFFID    LOGDT    LOGIN          LOGOUT                                      
    aw102      02/12/11                02/12/11 07.00                              
    aw102      02/12/11 02/12/11 18.00                                             
    aw102      03/12/11                03/12/11 04.30                              
    aw103      01/12/11 01/12/11 09.40                                             
    aw104      01/12/11                01/12/11 18.00                              
    16 rows selected.
    ===
    from the above table , I want to generate ouput as below:
    staffid  logdt      login             logout          diff-in-seconds   
    aw101    01.12.11   01.12.11 08.30    01.12.11 10.30  7200
    aw101    01.12.11   01.12.11 11.40    01.12.11 14.30  10200
    aw101    01.12.11   01.12.11 15.00    01.12.11 17.45  9900
    aw102    01.12.11   01.12.11 19.20    01.12.11 20.30  4200
    aw102    01.12.11   01.12.11 21.50    01.12.11 23.10  4800
    aw102    01.12.11   01.12.11 23.20    02.12.11 07.00  27600
    aw102    02.12.11   02.12.11 18.00    03.12.11 04.30  37800
    aw103    01.12.11   01.12.11 09.40
    aw104    01.12.11              01.12.11 18.00
    Here record aw102 & dt. 01.12.11 / 02.12.11, it should shows the next day out in
    the current date ie. 01.12.11.
    I dont know how to make query for the above output.
    please help me.

Maybe you are looking for

  • Podcast feed broken in two in "Podcast" view, but complete in "List" view iTunes 11

    Hi all, Today I updated to iTunes 11 on my Windows 7 laptop. When I went to update some podcasts I subscribe to I noticed that there were two lists for a couple of the different podcasts inthe defaualt view. I thought perhaps there was something wron

  • I need help to Configure the Encryption Key of btm

    In order to monitor the osb 11g. I have download OracleBTM_1of2.zip and I am trying to install it, so I am following this link http://download.oracle.com/docs/cd/E11857_01/install.111/e20124/install.htm#sthref20 how can I do this ? Configuring the En

  • Trouble with syncing my music.

    A while ago I deleted all of my music to make room for an update. Then I redownloaded my music using iCloud. Today I realized that all of my music wasn't there when I went searching for a song so I went to my iTunes to download it. Now my phone shows

  • My push notifications don't work in my iPhone 4, iMessage doesn't work too, what can I do?

    I have this iPhone, the push notifications don't work, iMessage doesn't work, I need help, I need to stay in the apps to receive messages for example what's app, Im+ pro, tango, viber, games, etc. the had jailbreak and I upgrade the iPhone to iOS 6.1

  • Why wont my iHome mouse work?

    I just recently got an iHome mouse and when I plug the USB in it says "configure keyboard. Press SHIFT+A random to key to submit keyboard." and when I click cancel I cant get it to come back up and the mouse doesnt work at all. yes the mouse has batt