Search code examples
sqloracle-databaserow-number

I want to get the last record from oracle using rownumber()


here am using oracle query for below record, i want to last rownumber 11 record.

     select max(t.atdatetime),
     t.lead,
     t.sysid,
     row_number() over(partition by t.sysid order by t.lead desc) as "number" from psd.psd_empreport t where t.sysid in(5350) group by t.lead, t.sysid   order by 2 desc

        SNO   datetime              tlcode  ecode  rownumb

         1  7/2/2013 6:00:25 AM      67    5350     1
         2  10/27/2014 8:30:34 AM   5508    5350    2
         3  10/24/2014 8:30:21 AM   5477    5350    3
         4  9/22/2012 12:28:20 AM   5051    5350    4
         5  10/10/2012 12:28:47 AM  4736    5350    5
         6  5/13/2014 8:24:21 AM    4459    5350    6
         7  9/12/2012 12:28:01 AM   3688    5350    7
         8  2/7/2013 12:32:34 AM    227     5350    8
         9  3/27/2013 12:34:39 AM   140     5350    9
        10  3/1/2013 12:33:27 AM    13      5350    10
        11  9/9/2014 8:28:41 AM     122     5350    11

Solution

  • i want to last rownumber 11 record.

    You just need to ORDER BY DESC in the ROW_NUMBER() window and then select the row having the row_number as 1 from the subquery.

    For example,

    SQL> SELECT *
      2  FROM
      3    ( SELECT empno, row_number() OVER(ORDER BY empno DESC) rn FROM emp
      4    )
      5  WHERE rn = 1;
    
         EMPNO         RN
    ---------- ----------
          7934          1
    

    So, make your existing query a subquery and filter the row_number as where rn = 1.