Need to fetch the last record/row from a table

Hi,
I have a requirement like fetching the closing balance of the last record of the table and inserting the same into the opening balance of the immediatetly created next record.
In simple words, I need to fetch a value from the last row of the record.
For example, I use the below query,
select rownum, empno, ename from emp
where rownum = (select count(rownum) from emp);
But, the above query does not return any of the record.
Hence, need help on this.
Regards,
Shivakumar A
Edited by: shiva on Mar 27, 2011 10:14 PM

Rows in a table are inherently unordered. In order to introduce the concept of "first" and "last", you would need to specify how to order the rows which would require that there was one or more columns in the table that you could order by in order to determine the "last" record.
In your closing balance example, if we assume that there is something like a BALANCE_DATE column,
SELECT account_number, balance_amount, balance_date
  FROM (
    SELECT account_number,
           balance_amount,
           balance_date,
           rank() over (partition by account_number order by balance_date desc) rnk
      FROM table_of_balances )
WHERE rnk = 1Justin

Similar Messages

  • Fetching more than one row from a table after selecting one value from the dropdown

    Hi Experts,
    How can we fetch more than one row from a table after selecting one value from the dropdown.
    The scenario is that I have some entries in the dropdown like below
      A               B               C        
    11256          VID          911256  
    11256          VID          811256
    11256          SONY      11256
    The 'B' values are there in the dropdown. I have removed the duplicate entries from the dropdown so now the dropdownlist has only two values.for eg- 'VID' and'SONY'. So now, after selecting 'VID' from the dropdown I should get all the 'C' values. After this the "C' values are to be passed to other methods to fetch some data from other tables.
    Request your help on this.
    Thanks,
    Preeetam Narkhede.

    Hi Preetam!
    I hope I understand your request proberly, since this is more about Java and less about WebDynpro, but if I'm wrong, just follow up on this.
    Supposed you have some collection of your original table data stored in variable "origin". Populate a Hashtable using the values from column "B" (let's assume it's Strings) as keys and an ArrayList of whatever "C" is (let's assume String instances, too) as value (there's a lot of ways to iterate over whatever your datasource is, and since we do not know what your datasource is, maybe you'll have to follow another approach to get b and c vaues,but the principle should remain the same):
    // Declare a private variable for your Data at the appropriate place in your code
    private Hashtable temp = new Hashtable<String, ArrayList<String>>();
    // Then, in the method you use to retrieve backend data and populate the dropdown,
    // populate the Hashtable, too
    Iterator<TableData> a = origin.iterator();
    while (a.hasNext()) {
         TableData current = a.next();
         String b = current.getB();
         String c = current.getC();
         ArrayList<String> values = this.temp.get(b);
         if (values == null) {
              values = new ArrayList<String>();
         values.add(c);
         this.temp.put(b, values);
    So after this, you'll have a Hashtable with the B values als keys and collections of C values of this particular B as value:
    VID --> (911256, 811256)
    SONY --> (11256)
    Use
    temp.keySet()
    to populate your dropdown.
    After the user selects an entry from the dropdown (let's say stored in variable selectedB), you will be able to retrieve the collection of c's from your Hashtable
    // In the metod you handle the selection event with, get the c value collection
    //and use it to select from your other table
    ArrayList<String> selectedCs = this.temp.get(selectedB);
    // now iterate over the selectedCs items and use each of these
    //to continue retrieving whatever data you need...
    for (String oneC : selectedCs) {
         // Select Data from backend using oneC in the where-Clause or whatever...
    Hope that helps
    Michael

  • How to get the last record of an internall table ....

    Hi All..
    i want to get the last record of an internal table itab, and i want the the value of the last record.

    Hi,
         Use describe statment.
    data: lv_line type i.
        Describe table itab lines lv_line.
        read table itab into wa_itab index lv_line.
    regards,
    Santosh Thorat

  • Read the last record of an internal table

    Hello All,
    I need to read the last entry of the internal table? Is it possible to achieve this without using loop - endloop?
    In the following example, I need to get the Batch '110776' and store it in a variable.
    ITAB:
    MATNR|CHARG
    010780|110770
    010780|110772
    010780|110773
    010780|110774
    010780|110775
    010780|110776
    Thanks.

    Use DESCRIBE to get the number of entires in variable last_entry
    and then use read table ....index last_entry

  • How to fetch the latest change number from CDPOS Table..?

    Hi All,
    im trying to fetch teh change number from CDPOS with the below select, but my requirement is always i wants to fetch the latest change number.
              SELECT SINGLE objectid changenr FROM cdpos
                     INTO wa_cdpos
                     WHERE objectid = wa_e1kna1m-kunnr
                     AND ( tabname = 'KNA1' OR tabname = 'KNVV')
                     AND   fname = 'AUFSD'
                     AND ( value_new = '01' OR value_new = space ).
    Please let me know how to achive this..?
    Ashok

    try this way
    "           SELECT SINGLE objectid changenr FROM cdpos
    "                 INTO wa_cdpos
               SELECT objectid changenr FROM cdpos
                      INTO table t_cdpos
                      WHERE objectid = wa_e1kna1m-kunnr
                      AND ( tabname = 'KNA1' OR tabname = 'KNVV')
                      AND   fname = 'AUFSD'
                      AND ( value_new = '01' OR value_new = space ).
    SORT t_cdpos by  changenr Descending.
    read t_cdos index 1.    "this is the latest change
    Prabhudas

  • Need to remove the page and components from jdr_paths table

    After running the following command
    BEGIN
    jdr_utils.deleteDocument('XX\oracle\apps\per\onlinepayslip\webui\XXOnline_PayPG.xml');
    END;
    commit;
    i ran the below select command and i can still see the data appearing for that path_name XXOnlinePayslip
    SELECT * FROM JDR_PATHS Where path_name like'OnlinePayslip%'
    how i can remove this entry from the JDR_PATHS table ...?
    Please help!

    Hi ,
    Since its an API can you try specifying the parameter name as well
    DECLARE
    BEGIN
    jdr_utils.deletedocument(p_document => 'XX\oracle\apps\per\onlinepayslip\webui\XXOnline_PayPG.xml');
    END;
    Please note that it will remove only extension / substitutioin / personalizaton .
    --Keerthi                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How do I get last 15 rows from a select query

    Hello,
    I am writing a query, and I need to filter the last 15 rows of from the select query.
    For example: Select id, name,join_date from emp order by join_date;
    So I need to get the last 15 rows from emp table so that we can who are the last 15 employees joined the organization. I want to show the result in ascending order, otherwise I would have taken first 15 rows with order by clause as descinding order.
    Thanks in advance,
    Param.

    SQL> select ename, join_date from test222
    2 where rownum < 6
    3 order by join_date
    4 /
    ENAME JOIN_DATE
    CNC5461177794 14-FEB-02
    OR91551178218 14-FEB-02
    TUB9894676495 14-FEB-02
    SG15431177117 14-FEB-02
    PIB9384674017 14-FEB-02
    SQL> SELECT * from
    2 (select ename, join_date from test222
    3 order by join_date desc)
    4 WHERE rownum < 6
    5 /
    ENAME JOIN_DATE
    II61111208401 19-MAR-02
    II61451208038 18-MAR-02
    PI20014184983 01-MAR-02
    BNF2221148037C 28-FEB-02
    UO78902581 18-FEB-02
    Can you see the problem now ?
    You can test this concept with your own table.
    have a good day,
    Sri

  • Fetching the last inserted record

    How can I fetch the last record inserted into oracle table?

    Hi Waleed / Bhavesh
    In pure RDBMS terms there is no concept of a first / last record. Also the query that Bhavesh has give makes an assumption that emp_n have been sequentially or inserted in some form of continuous incremental format.
    It is not adviseable to use ROWNUM and ORDER BY together since Oracle allocates ROWNUMs before it actually orders the data

  • Accessing the very last record in a transparent table.

    Hi!
    There's any way to read the last record of a transparent table?
    My problem is:
    I have to access the very las record of a Z table because I need the maximun value of a numeric field (that is the first field of the primary key).
    I used a SELECT MAX, with no condition , but I was asked to find a more performance solution.
    There is any way to access the last record of a table? Something like we have for the internal tables with the READ TABLE INDEX N, but with a select statement?
    Thanks a lot for your help!

    Yes, that was my first thought, but I made a comparising between both options with SE30.
    Check this numbers:
    TIME:  11,377,702
    select * from t100 into table t_t100.
    sort t_t100 descending.
    read table t_t100 index 1.
    TIME: 954,218
    DATA: MAX_MSGNR type t100-msgnr.
    SELECT MAX( MSGNR ) FROM T100 INTO max_msgnr.
    Select MAX is better...
    I don't think there is a better solucion... Maybe a big brain here has an idea...
    Vasanth, thanks for your quick reply!

  • Updating only the last record.

    Hi,
    I have a scenario where we get more than 1 record based on style. Everytime the new record comes in, I need to update the last record inserted. It requires a procedure to do it, but need some help on how to just update the last record only and not all the previous received records.
    Here is the scenario.
    create table test_1 as
    with data_Set as
    ( select 'ABCD' style, 20080101 date_received, 2 duration,20080301 expire_Date from dual union all
    select 'PQRS' style, 20080201 date_received, 2, 20080401 expire_Date from dual
    ) select * from data_set
    so now on next run when i get another record
    insert into test_1
    select 'ABCD' style, 20080401 date_received, 3 duration,20080701 expire_Date from dual.
    now the procedure should insert the incoming record and also update the expire_date for the previous record to a day before date_received for the new record. I am ok doing it when its only 2 records , but when i get another record of same style, i dont want to update all the previous received records. I only want to update the last record on file.
    can anyone suggest?

    STYLE     DATE_RECEIVED     DURATION     EXPIRE_DATE     SEQ_INSERTED
    110427     7/31/2006     0     7/31/2006     2
    110427     9/1/2007     12     9/1/2008     2
    110427     8/2/2008     24     8/2/2010     3
    468130     3/13/1997     0          2
    468130     3/13/1997     12     3/13/1998     2
    468130     1/12/2008     12     1/12/2009     3
    Here is my data set
    and here is the query i use to update, does it look correct?
    update test b
    set ( expire_Date) =
    (select start_date - 1
    from test a
    where (style_no, date_received) in
    (select style_no, max(date_received)
    from test c
    group by style_no
    and a.style_no = b.style_no
    and style_no in ('468130','110427')

  • Read the last record in the database table..

    Hi..
    I am new to ABAP. So i have one condition to read the address number field in the last record from database table by using the person number where clause field.
    But the person number is same for some the records.
    So can any tell me the logic for to read the addressnumber field in the last record of selected records from database where personnumber is equal to some thing.
    Please help me..
    Thanks
    venki

    Hi Venkat ,
    u mean to say
    person number  addressnumber
    aa1            0000000000001
    aa1            0000000000002
    aa1            0000000000003
    aa1            0000000000004
    aa2            0000000000021
    aa3            0000000000110
    if i have to read the addressnumber 00000000000004
    of the person number aa1
    u can go like
    data v_address number like addressnumber.
    sort itab by personnumber addressnumber
    loop at itab .
    at end of personnumber.
    move addressnumber to v_addressnumber ..
    endat.
    endloop.
    so using control break statements i can fetch the last record of my person number if at all the same person number is having more than one address number ..
    hope this helps,
    Regards,
    Vijay
    Message was edited by: Vijay

  • How can I get only the last 2 rows?

    How can I narrow down a query to get only the last two rows in a table ?
    Thanks,
    Mohan

    Thanks a lot Ram for your suggestion but already I have a query which returns a set of rows, of which I would like to further filter and get the last two rows
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Ramanuj Bangad ([email protected]):
    try out something like this if it helps.
    Example:
    select * from users
    where rownum <= (select count(*) from users)
    minus
    select * from users
    where rownum <= (select count(*) -2 from users )
    <HR></BLOCKQUOTE>
    null

  • SQL - Retriving Last 6 rows from Join of 2 Tables

    Hi All
    I want to retrive the last 6 rows from a query which has join of 2 tables
    Thanks in adv.
    Junu

    Hi,
    Check this.
    SELECT e.empno, e.deptno, e.sal,e.rn
    FROM (
         SELECT ROWNUM rn, a.empno, b. deptno, a.sal,
              ( SELECT COUNT(1) FROM scott.emp c, scott.dept d
                        WHERE c.deptno = d.deptno ) max_rn
    FROM scott.emp a, scott.dept b
              WHERE a.deptno = b.deptno
         ) e
    WHERE rn BETWEEN max_rn -6 AND max_rn     
    ORDER BY rn     
    Regards
    K.Rajkumar

  • How to: Display Last n Rows in a table

    I am currently running Crystal Reports XI and have been tasked with developing a report that displays only the last 30 rows in a table in ascending order (the records are used for showing data trends over time in a line graph). I have created a Command to extract the records, and by using the TOP 30 statement I can get the first 30 rows in proper order; however, in order to get the last 30 rows I have to sort the records in descending order. This gives me the last 30 rows that I need, but the data is in descending order. Is there another way to get the last 30 rows in a table so that the records come out in ascending order?
    The Command I am using looks like this:
    SELECT TOP 30 ROWID FROM MYTABLE ORDER BY ROWID DESC
    (The ROWID field is alpha numeric)

    Hi,
    Create a Group based on Rowid in the order-Ascending. This Group should contain all the fields that you require to print along with Rowid.  Therafter insert Summary like sum,count etc for for any field within the group of the type numbervar(numeric). This would activate the Group Sort Expert in the Report Menu. Click on it and select Bottom N (with N as 30) within nature of Sort and suppy the fieldname as Rowid.
    Hope this solves.....
    Thanks,
    Amogh.

  • Displayin message and fixing the number of rows in a table

    Hi Experts,
    I have a requirement like this
    there is a table, where i need to diplay a message when there are no records and no rows should be visible on that table.
    Also, when the records are populated from the context, i need to fix the number of rows in that table and display the records.
    Please let me know hw this can be achieved.
    Also in the table I have Link to URL, please let me know how to handle this reference, when i set the reference Property, its giving me an error stating that the file doesn't exist when the table gets loaded.
    Thanks in Advance
    Regards,
    Palani

    Hi
    Oh!!  You should to  explain it at first thread itself that you want to display a JPG imange or other WDWebResourceTypetaken form the backend.
    1. So this is not at all a URL
    2. You have to convert binary data to WDWebResource then display it in either Image UI element or other (like PDF , txt etc)
    3
    try
                   //        Read the datasource of the FileUpload
                   IWDResource res = wdContext.currentContextElement().getResource();
                   InputStream in = res.read(false);
                   ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                   int length;
                   byte[] part = new byte[10 * 1024];
                   while ((length = in.read(part)) != -1)
                        bOut.write(part, 0, length);
                   in.close();
                   bOut.close();
                   IPrivateUploadCompView.IImageTableElement ele = wdContext.nodeImageTable().createImageTableElement();
                   ele.setImage(wdContext.currentContextElement().getResource().getUrl(0));
                   ele.setText(res.getResourceName());
                   wdContext.nodeImageTable().addElement(ele);
              catch (Exception e)
                   wdComponentAPI.getMessageManager().reportWarning(e.toString());
    Here I assume that you convert that data to IWDResource type or
    4.
    WDWebResource.getWebResource(wdContext.currentContextElement().getresource(), type);
    // getResource of type binary which u read from BAPI and set it in local context , type is MIMETYPE or hardcode it as "JPG"
    5. Further help
       [Help1|To Displayan Image in Webdynpro Java from Standard Function Module;
    [Help2|http://wiki.sdn.sap.com/wiki/display/KMC/GettinganimagefromKMDocumentstobeusedinWeb+Dynpro]
    [Help3|http://wiki.sdn.sap.com/wiki/display/KMC/GettinganimagefromKMDocumenttobeusedinWeb+DynPro]
    It might code look strange at first , please do some reserch in SDN ,I did my best at this level.
    Best Regards
    Satish Kumar

Maybe you are looking for

  • Vendor Evaluation Report

    Hi All, We have a problem. The vendor evaluation report is not considering the rejections of goods and shows the quality as 100. The client has not maintained any scores for quality. This may be the reason, or is it mandatory to have QM module to eva

  • Call functions between classes

    Hi all, I have two java classes compiled into the DB in different schemas. How could I call the static method in classA from classB? I suppose I need to get the schema name in there somehow, or is it just as simple as classA.method(arg1) havent dared

  • Safari with an iBook G4 (1.33Ghz)?

    Hello Everyone, What is the best version of Safari to use with an iBook G4 (1.33Ghz)? Currently has 512mb RAM and upgrading to a total of 1.5. Many thanks in advance.

  • I cannot print any adobe documents.

    Whenever I try to print the document, a box pops up that says the document cannot be printed.  Then it says that no pages were selected to print.  But pages WERE selected to print.  I selected them every way possible, even one at a time,and it will n

  • How to display contents from a database to a jsp page

    hi im using hibernate , i want to display the conetents from a databse to jsp page which is having a form i want to get the data on the form fields after changing the values i want to write it back to the database im using struts and hibernate im str