How to get last row and sum of all columns in one query

Hi ,
is there a way to get last record for a column and sum of all record for another column in the same query.
Best Regards ,

You should define your requirements properly for volunteers to help here..
Your data is not good enough to provide you accurate solution. Reason being you dont have a proper column which differentiates between first and last entry.
The solution becomes easy based on your desgin.
I have introduced a grouping column called "id" and a time column called "time_of_insert" (only this way you can confidently say that you can differentiate between first and last (also a fool proof solution) --- you may optionally use sequence(instead of date though if you say you may end up inserting two rows at the same time, then probably sequence would be a better choice to differentiate rather than a timestamp field) etc...)
With your sample data something like this can be done to achieve your desired result.
WITH dataset AS
        (SELECT 1 id,10 used, 8 remain,systimestamp+1/24 time_of_insert FROM DUAL
         UNION ALL
         SELECT 1 id, 1, 7,systimestamp+2/24 FROM DUAL
         UNION ALL
         SELECT 1 id,2, 5,systimestamp+3/24 FROM DUAL
         UNION ALL
         SELECT 1 id,1, 0,systimestamp+4/24 FROM DUAL
         UNION ALL
         SELECT 1 id,0, 0,systimestamp+5/24 FROM DUAL
         UNION ALL
         SELECT 1 id,1, 4,systimestamp+6/24 FROM DUAL)
SELECT *
  FROM (SELECT SUM (used) OVER () sum_all,
               FIRST_VALUE (remain)
                  OVER (PARTITION BY id ORDER BY time_of_insert DESC)
                  last_row
          FROM dataset)
WHERE ROWNUM = 1;
Output:
SUM_ALL       LAST_ROW
15                  4
Cheers,
Manik.

Similar Messages

  • How to get the Row and Column values in ALV (without using Objects)

    Hi All,
    I need to get the Row / Column when double click is used in ALV, I can use the double click event for this. However, I do not want to use the Object Oriented ALV. I want to implement the same functionality using general (using functions) ALV.
    Is there any way to get the row / column values for a Generia (non-OOPs) ALV report.
    Please help.
    Thanks,
    Vishal.

    Hello,
    The only think you have to do is to get the index where the user clicked, and then read the internal table you sent to the alv
    CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
        EXPORTING
          i_callback_program       = 'prg_name'
          i_callback_pf_status_set = 'SET_PF_STATUS'
          i_callback_user_command  = 'USER_COMMAND' " this is to the click event!!
          i_callback_top_of_page   = 'TOP_OF_PAGE'
          is_layout                = alv_layout
          it_fieldcat              = alv_fieldcat
          i_save                   = 'A'
          it_events                = alv_events[]
        TABLES
          t_outtab                 = i_totmez.  ---> TOUR IT.
      IF sy-subrc <> 0.
        MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
              WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
      ENDIF.
    " then....
    FORM user_commandUSING r_ucomm     TYPE sy-ucomm
                                    ls_selfield TYPE slis_selfield.
    " r_ucomm -> HAS THE STATUS
    " ls_selfield-tabindex  -> HAS THE SELECTED INDEX
    " THEN READ THE INTERNAL TABLE
    " HERE YOU WILL HAVE THE SELECTED ROW
    READ TABLE i_totmez INDEX ls_selfield-tabindex.
    ENDFORM.
    cheers,
    Gabriel P.

  • How to get video file and iTunes Extra to show as one file in iTunes?

    When I purchase a movie in iTunes with iTunes Extras, after the download is finished in the "Movies" and "Genres" view they appear as one file. You click on the cover, it opens, shows the "Play iTunes Extra" button as well as a small Play arrow button next to the title to play the movie directly. Only in "List" view do they appear as separate files.
    How can I achieve that for my own iTunes extra? I tried giving the .ite the same XID as the movie file but that didn't work, they continue to appear as separate files in iTunes and the little play button when expanding the iTunes Extra doesn't work obviously. Anyone can tell me how this is done?

    Ok, I finally figured it out... there is 2 files that play a critical role in this
    first is manifest.xml
    in this file ensure that the library_item type string references the xid for your video file, and it has to be a proper xid. The iAd Producer manual explains how to create one if it does
    example:
    <library_item type="video" local_id="feature" xid="TEST:uuid:C7AE7CED-3F60-4C08-AA01-E3F9647B95CC" name="Your Movie"/>
    second file and even more critical is iTunesMetadata.plist. There is a couple of strings in there that lace the iTunes Extra to the film and vice versa
    <key>itemId</key>
    <integer>987654321</integer>
    <key>itemName</key>
    <string>Your Movie - iTunes Extras</string>
    The first is a unique 9 digit number that identifies your iTunes Extra file, the second is the name of the file that should follow the convention "Your Movie Title - iTunes Extras"
    <key>playlistId</key>
    <integer>123456789</integer>
    <key>playlistName</key>
    <string>Your Movie</string>
    This is what ties it back to the movie file, we will come back to it later where in the movie MetaData you need to place this 9 digit string
    <key>xid</key>
    <string>TEST:uuid:C7AE7CED-3F60-4C08-AA01-E3F9647B95CC_ITUNES_EXTRAS</string>
    This is the convention in how to properly xid your iTunes Extra, it is your movie's XID with "_ITUNES_EXTRAS" added to the end of it
    <key>Name File</key>
    <string>Your Movie - iTunes Extras.ite</string>
    <key>associated-adam-ids</key>
    <array>
    <integer>123456789</integer>
    The first is self explanatory but the second is again this 9 digit number that you will need to place into the meta data of your movie. It is what will make iTunes lace the two files together
    <key>xid-asset-mapping</key>
    <dict>
    <key>TEST:uuid:C7AE7CED-3F60-4C08-AA01-E3F9647B95CC</key>
    <array>
    <integer>123456789</integer>
    </array>
    <key>TEST:uuid:C7AE7CED-3F60-4C08-AA01-E3F9647B95CC_ITUNES_EXTRAS</key>
    <array>
    <integer>987654321</integer>
    </array>
    </dict>
    This is the last critical piece, it laces the two files tigthly together. Now the 9 digit number counting down from 9 is part of the unique ID of the iTunes Extra, the 9 digit number counting up from 1 needs to be put into the metadata of your movie. The annotation type for this is "contentID".
    That's pretty much it. If you did it right your files will now appear as one file in cover view just like a movie bought in the store.
    The easiest to do this right is to grab the manifest.xml and iTunesMetadata.plist from an iTunes store movie and copy paste and edit it for your purposes, which is what I did.
    Cheers everyone!

  • How to get SCOM alerts and send single summary email of one's that have breached.

    Hi,
    I'm trying to create a runbook which does as the title suggests, ie I want to get the 'Active' alerts from the console which have breached our SLA, which is No Critical or Warning alerts in resolution state of New for more than 24 hrs, and emails this list
    to an internal Distribution List of all the potential service owners.  Its just intended as a daily email to poke the relevant people not to ignore the console alerts :-)
    I'm able to Get Alerts OK, but from there I'm having diffs.  I have been given a powershell (as I'm no good at Powershell myself) which does the filtering to get the relevant breached alerts, but when I pass output to other activities and ultimately
    to the create/send email, I end up only able to get multiple emails, one be alert which matches the filtering from powershell.  I have appended to a file to check that I can write the alert properties line by line, but for example if Ive 4 alerts then
    I end up with 4 emails - I want one email with each alert detail (severity, Alert name, path,resolutionstate, Days/hrs in breach, Service Owner (custom Field 3) etc).  I have toyed with flattening the output with line breaks and/or commas at various points
    along the activity chain to ftry force a single iteration of te send email but this just messes the format to the point of not being useful.
    So was wondering if anyone could advise if this is possible, esp if able to do it using the standard activities  along with SCOM IP - I'm sure doing it all in powershell it a possible answer but I'm not proficient to do it - unless someone can provide
    said script! :-)
    Another possibility which has crossed my mind is to possible query the OpsMgr DB directly using the Alert ID from Get Alert but haven't tried tht yet.  I think I' stuggling to understand the basic of how the data is passed from activities esp using
    the 'flatten outpout method..  My current runbook has the fllowing activities:
    GetAlert -> Run .Net (powershell for filtering for breaced alerts) -> AppendFile (to Check the alert output) -> Create/Send Email(to send summary email).  What happens is if I have say 4 Breached emails in Console, when I run tester I
    see GetAlert runs Once detail shows it has found 4 alerts), then each activity up the chain runs 4 times so that finally I end up with 4 emails.
    If anyone has any suggestions it would be much appreciated - I can provide any more details/upload pic of current runbook if it helps...
    Thanks...

    Hi thanks for the suggestion.  I've tried playing around with the runbook using the Junction activity infront of the sendmail.  It doesnt appear to do anyting in itself (unless I'm not using it correctly).  The only way I can get the email
    to only send once is if I flatten the output from the returned data behaviour - this works if I flatten at the Get Alert stage without the Junction activity or if I use the junction an flatten it then the email fires once.
    However the problem with this is that each field for each alert is written vertically, so if I have 3 alerts returning 3 pieces of returned data I get:
    <Alert1 datafield1>
    <Alert2 datafield1>
    <Alert3 datafield1>
    <Alert1 datafield2>
    <Alert2 datafield2>
    <Alert3 datafield2>
    <Alert1 datafield3>
    <Alert2 datafield3>
    <Alert3 datafield3>
    wereas I wan the dat to appear in horizonally with each alert details on each row as like when written to a file, ie
    <Alert1 datafield1> <Alert1 Datafield2> <Alert1 DataField3>
    <Alert2 datafield1> <Alert2 Datafield2> <Alert2 DataField3>
    <Alert3 datafield1> <Alert3 Datafield2> <Alert3 DataField3>
    Without the use of flatten, the email which fires once for each alert has the data displayed correctly.  So essentially what I'm hoping to get is all returned alert details one per line/row in the body of the email...
    If theres any easy way to do it withing the orchestrator activities would be great.  Otherwise it looks like I might have to try find a powershell or SQL script to pull back alert data.  Cheers...

  • How to get terminate status and number of all steps executed in Teststand

    Hi ! Could someone teach me,pls?
    1. Query:
        How can i get the sequence status of Terminated?
        Aim:
        I want to Terminate  sequence execution while something wrong happened, then i want to aquire the Terminated Staus.
        My action:
        i add a ActiveX API step into a callbacks file called SequenceFilePostStepFailure , but i can't get the value well 
    2. Query:
        How can i get the number of all steps executed in Cleanup of one sequence?
        Aim:
        I  want  to get the number of all steps executed include Setup, Main and Cleanup, after i terminating the sequence
        My action:
        call a variable from RunState.NumStepsExecuted . but it only the number of steps executed from Setup or Main or Cleanup , not all.
    Thank you in advance!
    Solved!
    Go to Solution.

    AllanXu wrote:
    Hi ! Could someone teach me,pls?
    1. Query:
        How can i get the sequence status of Terminated?
        Aim:
        I want to Terminate  sequence execution while something wrong happened, then i want to aquire the Terminated Staus.
        My action:
        i add a ActiveX API step into a callbacks file called SequenceFilePostStepFailure , but i can't get the value well 
    2. Query:
        How can i get the number of all steps executed in Cleanup of one sequence?
        Aim:
        I  want  to get the number of all steps executed include Setup, Main and Cleanup, after i terminating the sequence
        My action:
        call a variable from RunState.NumStepsExecuted . but it only the number of steps executed from Setup or Main or Cleanup , not all.
    Thank you in advance!
    1. Execution.GetStates() - look at the termination status. Termination is an execution specific state, not a thread state.
    2. You could use a PostStep callback and do the counting yourself (e.g. in a file global or station global variable), however there is a performance cost to poststep callbacks so it depends on whether or not it's worth the performance cost in your particular use case.
    Hope this helps,
    -Doug

  • How to get current month and last month dynamically??

    how to get current month and last month dynamically
    like
    month = getCurrentMonth();
    lastmonth = getcurrentMonth() -1;
    please help
    thanks

    hi :-)
    /* depracated but can be still useful */
    java.util.Date dtCurrent = new java.util.Date();
    int month = dtCurrent.getMonth();
    int lastmonth = dtCurrent.getMonth() - 1;
    System.out.println("* " + month);
    System.out.println("* " + lastmonth);
    /* better to use this one */
    Calendar cal = new GregorianCalendar();     
    int imonth = cal.get(Calendar.MONTH);
    int ilastmonth = cal.get(Calendar.MONTH) - 1;
    System.out.println("*** " + imonth);
    System.out.println("*** " + ilastmonth);
    regards,

  • How to get the row Count of a ResultSet

    How to get the row Count of a ResultSet

    Hi
    I'v tried rennie1's way ,but I only get zero,my code is:
    rs.executeQuery("select count(*) from t_test");
    if (rs.next()) int rowCount=rs.getInt(1);
    I also tried barni's way ,but the method rs.last() and rs.beforeFirst() throw a same Exception
    I tried another way,the code is:
    while rs.next(){
    // Do nothing ,just move the cursour to the last row
    int rowCount=rs.getRow()
    However,the rowCount still equal zero
    Any help would be greatly apprecite!
    note:
    I get connection by DataSource's JNDI name from client, the Server is Weblogic Server 6, the DBMS is Oracle.

  • How to get  visible row  count  in JTable ?

    I have one table which is added to one scroll pane. For example my table have total 1000 rows, but at a time only 20 rows should be visible to the scroll pane. And I want to scroll the rows and show only 20 at a time.When user scrolls JTable then next time he can view only 1 to 21, then 2 to 22, and so on. I want to know how to get that number which represents the visible row( in this case it is 20).So kindly help me how to get visible row count. Any help regarding this will be appriciated.
    Thanks and Regards,
    Sheetal

    how to get visible row count.First you need to get the viewport used by the scrollpane. Then you can use methods like getViewPosition() and getViewSize() to get information about the current postition of and size of the viewport.
    Then you can use the table method getRowAtPoint(). to determine the first and last visible row which can then be used to calculate the visible row count.
    When user scrolls JTable then next time he can view only 1 to 21, then 2 to 22, and so onThis is the default behaviour when a "block" scroll is done.
    However when you click on the arrow button on the scrollbar it will only scroll a single row. You could override the getScrollableUnitIncrement() method to return the value from the getScrollableBlockIncrement() method.
    However the user can still drag the scrollbar manually which would cause a problem. So you would also need to remove the MouseMotionListeners from the scrollbar to prevent this.

  • How to find accurate number of Rows, and size of all the tables of a Schema

    HI,
    How to find the accurate number of Rows, and size of all the tables of a Schema ????
    Thanks.

    SELECT t.table_name AS "Table Name",
    t.num_rows AS "Rows",
    t.avg_row_len AS "Avg Row Len",
    Trunc((t.blocks * p.value)/1024) AS "Size KB",
    t.last_analyzed AS "Last Analyzed"
    FROM dba_tables t,
    v$parameter p
    WHERE t.owner = Decode(Upper('&1'), 'ALL', t.owner, Upper('&1'))
    AND p.name = 'db_block_size'
    ORDER by 4 desc nulls last;
    ## Gather schema stats
    begin
    dbms_stats.gather_schema_stats(ownname=>'SYSLOG');
    end;
    ## Gather a particular table stats of a schema
    begin
    DBMS_STATS.gather_table_stats(ownname=>'syslog',tabname=>'logs');
    end;
    http://www.oradev.com/create_statistics.jsp
    Hope this will work.
    Regards
    Asif Kabir
    -- Mark the answer as correct/helpful

  • How to get current row data in table control

    Hi , expert ,
       I am professional in oracle ,  but  now I am a new guy in SAP ABAP .
    I  have a question in UI
    How to get current row data and click pushbutton  in table control  to open next screen ?
    I want to get the current data and open next screen to carry out detail detail .
    Thansk for all your suggestion .

    GET CURSOR LINE SY-CUROW .
      READ TABLE internal_table index SY-CUROW.

  • How to get selected  row index  of a Table ?

    hi gurus,I'm new  to Webdynpro for abap
    I'm displaying    just Flight details in a Table  so
    how to get selected  row index  of a  Table  and need  to be display in Message manager.

    Hi,
    For getting the row index use the following code.
    DATA lo_nd_node TYPE REF TO if_wd_context_node.
      DATA lo_el_node TYPE REF TO if_wd_context_element.
      DATA index TYPE i.
    * navigate from <CONTEXT> to <NODE> via lead selection
      lo_nd_node = wd_context->get_child_node( name = wd_this->wdctx_node ).
      lo_el_node = lo_nd_node->get_lead_selection(  ).
      index = lo_el_node->get_index( ).
    node is the name of the node which is binded to the table.
    For printing the message u can use code wizard.
    Press ctrl-F7. Now Select generate message.
    IN this select the method  REPORT_SUCCESS
    In the code now u can give index to Message text Exporting parameter. Comment receiving parameter.
    Write the whole code in onLeadSelect of the table.
    Regards,
    Pankaj Aggarwal

  • How to get Current row of ViewObject in the DoDML methode

    Hi all
    I have two ViewObject EmplyesView and DeptView
    How to get Current row of ViewObject DeptView in the DoDML methode of EmplyesView

    OK, we can play this game on and on...
    I'll ask for a use case (http://en.wikipedia.org/wiki/Use_case) and you don't give any info we don't already know. After an other 10 posts we probably know what you real problem is and can give you the advice which you could have gotten in the fist place.
    So please take some time and describe the problem as if you would ask your mother for help. Tell us how the data model is build and how the VO are related. Is there any input from an user involved? Which information from the other view do you need? How do you get to the doDML method? Is there a button in the ui involved?
    Timo

  • How to Increase the Rows and Columns Size of Bex Query in Enterprise Portal  of SAP  7.3

    Dear All,
    Please let me know the process how to Increase the Rows and Columns  Size of Bex Query in Enterprise Portal  of SAP  7.3 .
    Currently I am getting Only  4 columns and 10 rows in One Page .And I am getting 1,2 etc tabs for both row and column. So i want to increase the column length more than 100  and row length more than 10000.
    Please suggest me a suitable solution to over come this issue.
    Please find the Below screen shot.
    Thanks
    Regards,
    Sai

    Dear All,
    Please find the attached screen shot.
    The report be open with 4 or 5 columns and 5 or 6 rows.
    So, please  let me know how to increase the length of the table.
    Do the needful for me to over come this issue.
    Thanks
    Regards,
    Sai.

  • How to get last column used in report sorting?

    hi,
    how to get last column used in report sorting?
    simon

    How to identifiy which column was sorted having different reports on page?
    just use:
    'YOUR_STATIC_REGION_NAME' instead of p_static_id,
    :APP_ID for p_app_id,
    :APP_PAGE_ID for p_page_id
    :APP_USER_ID for p_app_user.
    and dont forget to grant SELECT on #OWNER# to APEX_030200.WWV_FLOW_PREFERENCES$
    good luck and thank you Juergen.Schuster
    Simon

  • Get Last Row Excel VI

    Hello Everyone
    I came across the VI attached  on 
    https://decibel.ni.com/content/docs/DOC-22422
    (Below is my modified LV 2010 version but it is not much different)
    I understand that you are able to put in numerical data but in a single row I want to be able to have numerical data, words, and a URL.
    I think you have to use the Append Image to Report for the URL part but does anyone understand why it has to be 2D array if I just want the
    last row to put in all my data. I do not know where or how I can add just words to this last row or the image.
    Any help is appreciated.
    xxxMidna19 
    Attachments:
    Write%20Row%20of%20Data%20to%20Excel%20Spreadsheet%202010[1].vi ‏19 KB

    There are two questions, so here are two answers.
    Question 1 -- how do you mix numbers, strings, and URLs?  Answer -- convert everything to strings (which, I believe, is what happens internally -- indeed, the input is labelled Text Data).
    Question 2 -- why do you need to pass in a 2-D array if you are only writing a single row?  Answer -- the "generic case" is to write an entire table, i.e. rows and columns, or a 2-D array, all at once.  As a "special case", you can accept a single row if you convert it to a 2-D array (1 row, many columns) simply by passing it through a Build Array block.  Thus you can have a single function Append Text Table to Report handle both multi-line text tables and single-line (faked to appear as though it were multi-line) text tables.

Maybe you are looking for

  • How can I work with Bahnhof.se and airport extreme

    hej, I bought airport extreme and startedwith Bahnhof.se 100/100 The problem is that I can activate only one dator. But I possess iPad, mini iPad 2 iphones and macbook air When I need my macbook, I have to activate this dator on Bahnhof.se and my iPa

  • Fonts in Indesign CS6

    I have recently downloaded the new Indesign CS6 and now my fonts are showing up as an error. I've tried copying all my fonts and adding them to the Indesign folder but they are still showing as an error. Please help.

  • Reg.table and screen connectivities

    Dear Experts I want to save and retrieve some data like Emp Name,Emb No,Address and Cell number by creating new table and fields. How to implement this, what are the steps,how to connect the table with the screen. Pls explain in greate details. Thank

  • [svn] 1535: Merge change BLZ-1520 from 3.0.x to trunk.

    Revision: 1535 Author: [email protected] Date: 2008-05-02 10:43:13 -0700 (Fri, 02 May 2008) Log Message: Merge change BLZ-1520 from 3.0.x to trunk. Ticket Links: http://bugs.adobe.com/jira/browse/BLZ-1520 Modified Paths: blazeds/trunk/apps/samples/WE

  • Question about queries

    I am using several ways to build queries : mySession.readObject mySession.readAllObjects mySession.executeQuery and classes ReadObjectQuery, readAllQuery and readQuery What are the differences between all this classes and methods ??? I also used quer