"Select sum(field)" not summing

I have a PLSQL statement like:
select sum(field1) sum1,
sum (field2) sum2
into v_sum1,
v_sum2
where something = somethingElse;
How come my variable are being assigne a single row's (the first) field1 and field2 values rather than the actual sums?
If I do a SQLPLUS version of this (without the "into" part), I get the correct sums returned in a single row.
Thanks,

I just tried your query and it should work if you only want a sum for a specific where clause. For example one employee's salary given the employee's id. If you want a list of salaries for every employee in a specific department, you need to put this into a cursor and loop through it.
This will look at all the rows based on the where statement and sum them all up. The reason it works in SQL*PLUS is that an implicit cursor is used (loops through automatically).
ex:
DECLARE
CURSOR C_SUM is
select ename,
sum(sal) sum1,
sum(comm)sum2
from emp
where deptno = 30;
BEGIN
FOR R_SUM IN C_SUM
LOOP
DBMS_OUTPUT.PUT_LINE(r_sum.ename ||' '||
r_sum.sum1 ||' '||
r_sum.sum2);
END LOOP;
END;
Make sure if you use DBMS_OUTPUT you have serveroutput on. Hope this helps. If it doesnt, post the actual code you are having problems with.

Similar Messages

  • Selection screen field not accepting 0 as a value

    i have declared a field in the selection screen as
    SELECT-OPTIONS:  s_level    FOR  crmm_territory-level_id .
    and this field will comprise of values from 0-9. but when im executing the report this field is not accepting 0 as a value, instead it is treating it as a blank and providing me all the values for s_level from 0-9.
    its working fine with any other value and is displaying their respective values for 1-9
    only problem is when i give the value as zero.
    also in the debugger i tried to IF s-level[] is not initail...its showing it as initial
    while i have provided it a value of 0.
    thanks.

    Hello Divya,
    If you are giving 0 in the select-options....
    if that field is numeric... it means that it is inital.
    If that field is character... then it will display the result accordingly.
    Check with the data element of the reference field.
    Reward If Helpful
    Regards
    Sasidhar Reddy Matli.

  • Selection screen field not working in Query

    Hi Gurus!
    I have a small problem with one of my query that I just created for finding status of our customers. I have a code section which handles it all . The problem is that I ahve a user field called "Check date" which I ahve used in selection screen as well as the layout, when I put a value in this field in the selection screen the report dosent give any output " NO data to display" but when I leave it open it does give me the out put with the saem check date as I ahd entered earlier in my selection screen.
    I am not sure where my selection code is working wrong . Could anyone please help me out please.
    DATA: ls_vakpa LIKE vakpa.
    DATA old_date LIKE sy-datum.
    old_date = key_date - num_days.
    status = 'ACTIVE'.
    check_date = old_date.
    * (If I entere this field (check_date) with any date
    *  and run it does not give me output and without
    * entry it dioes give output.
      SELECT SINGLE * FROM vakpa INTO ls_vakpa
          WHERE kunde = kna1-kunnr
       AND audat > old_date.
          IF sy-subrc <> 0.
        SELECT SINGLE * FROM vakpa INTO ls_vakpa
            WHERE kunde = kna1-kunnr
          AND audat < old_date.
          IF sy-subrc = 0.
          ls_audat = ls_vakpa-audat.
          ls_vbeln = ls_vakpa-vbeln.
        ELSE.
          CLEAR ls_audat.
          clear ls_vbeln.
        ENDIF.
        status = 'INACTIVE'.
      ELSE.
        ls_audat = ls_vakpa-audat.
        ls_vbeln = ls_vakpa-vbeln.
      ENDIF.
    Edited by: Rob Burbank on Apr 7, 2010 12:08 PM

    DATA: ls_vakpa LIKE vakpa.
    DATA old_date LIKE sy-datum.
    old_date = key_date - num_days.
    status = 'ACTIVE'.
    check_date = old_date.
    if old_date is initial.
       old_date = key_date - num_days.
       check_date = old_date.
    endif.
      SELECT SINGLE * FROM vakpa INTO ls_vakpa
          WHERE kunde = kna1-kunnr
    *      AND audat > old_date.
        AND audat > check_date.
      IF sy-subrc <> 0.
        SELECT SINGLE * FROM vakpa INTO ls_vakpa
            WHERE kunde = kna1-kunnr
    *        AND audat < old_date.
          AND audat < check_date.
        IF sy-subrc = 0.
          ls_audat = ls_vakpa-audat.
          ls_vbeln = ls_vakpa-vbeln.
        ELSE.
          CLEAR ls_audat.
          clear ls_vbeln.
        ENDIF.
        status = 'INACTIVE'.
      ELSE.
        ls_audat = ls_vakpa-audat.
        ls_vbeln = ls_vakpa-vbeln.
      ENDIF.

  • Selection Screen - Field dehighlight

    Hello All,
    How can i make an Selection screen field not as an Input field.
    The field is a parameter P_GJAHR which will always be set to 2005. So, i would like to see FY 2005 on the selection screen field as dehighlighted.
    Would be glad if views are provided on this.
    Regards,
    - PSK

    PARAMETERS : P_GJAHR LIKE BKPF-GJAHR MODIF ID SG1.
    AT SELECTION-SCREEN OUTPUT.
      LOOP AT SCREEN.
        IF SCREEN-GROUP1 = 'SG1'.
          SCREEN-INPUT = '0'.
          MODIFY SCREEN.
        ENDIF.
      ENDLOOP.
    Hope this helps,
    Erwan.

  • Performance Measure - Select SUM and Collect Statement.

    Dear All,
    I am using YNME_PROCESS_PO_CUST Badi in this i writing some validation Delivery Completion.
    For that i need to calculate GR qty and Delivery quantity based on this i need some validation. But here i confussed which statement i need to use for bast performance.
    Note: In Badi Item Level Data will be process one by one..like item level 10 then 20 then 30......Like that
    Code will like that---
    SELECT  SUM( menge )  FROM ekes
                                INTO  l_delqty
                                WHERE ebeln =  ls_mepoitem-ebeln
                                AND   ebelp =    ls_mepoitem-ebelp.
            SELECT  SUM( dabmg  )  FROM ekes
                             INTO  l_grqty
                             WHERE ebeln =  ls_mepoitem-ebeln
                             AND   ebelp =  ls_mepoitem-ebelp.
            l_delqty1 =  l_grqty - l_delqty.
            IF l_delqty1 NE 0.
              ls_mepoitem-elikz = ''.
              CALL METHOD im_item->set_data( ls_mepoitem ).
            ENDIF.
    I check in SE38 response is better in this code.
    Other code may be like that .. same data will be like upper/
          SELECT * FROM ekes
                     INTO CORRESPONDING FIELDS OF TABLE it_ekes
                     WHERE ebeln =  ls_mepoitem-ebeln
                     AND    ebelp =   ls_mepoitem-ebelp.
          LOOP AT it_ekes.
            MOVE-CORRESPONDING it_ekes TO it_ekes1.
            COLLECT it_ekes1.
            CLEAR  it_ekes.
          ENDLOOP.
          READ TABLE it_ekes1 INDEX 1.
          IF sy-subrc EQ 0.
            l_delqty1 =  it_ekes1-menge - it_ekes1-dabmg.
          ENDIF.
        IF l_delqty1 NE 0.
              ls_mepoitem-elikz = ''.
              CALL METHOD im_item->set_data( ls_mepoitem ).
       ENDIF.
    Can any send me document--
    Regard
    DK

    Hi,
    Single Select statement is certainly better.
    But no need to do select * and using into corresponding fields. These will reduce the performance. Also the loop statment is not absolutely correct. Following could be a sample code.
    TYPES: BEGIN OF gx_ekes,  (maintaining same sequence of fields as in select statement, this way no need of into corresponding fields)
                 ebeln type ebeln,
                 ebelp type ebelp,
                 menge type bbmng,
                 dabmg type dabmg,
                 END OF gx_ekes.
    DATA : lit_ekes TYPE TABLE OF gx_ekes,
                git_ekes TYPE TABLE OF gx_ekes,
                wa_ekes TYPE gx_ekes.
    SELECT ebeln
                  ebelp
                  menge
                  dabmg
    FROM ekes
      INTO TABLE it_ekes
    WHERE ebeln = ls_mepoitem-ebeln
    AND ebelp = ls_mepoitem-ebelp.
    LOOP AT lit_ekes INTO wa_ekes.
    COLECT wa_ekes INTO git_ekes.
    CLEAR: wa_ekes.
    ENDLOOP.
    CLEAR: lit_ekes.
    Now the first record in git_ekes will have the sum as only one line item is being passed in the user exit.
    Regards,
    Pranav.

  • Select - SUM - inner join

    Hi,
        select sum( a~dmbtr )
              into o_debit
              from bsik as A inner join FAGLFLEXA as B
                on abukrs = bRBUKRS
               and agjahr = bRYEAR
               and abelnr = bdocnr
             where a~bukrs = x_bukrs
               and a~lifnr = p_lifnr
               and a~shkzg = 'S'
               and a~budat in s_budat
               and a~hkont gt '0000000000'
               and a~hkont le '9999999999'
               and b~prctr = p_prctr.
    Above query is not giving result in o_debit though data is available in both the table. Please guide me, if I have written something wrong.

    Hi, Raj.
    Test the following Sample It is working fine for me hope will work for you too, I did some little change.
    TYPES: BEGIN OF ty_test,
      dmbtr LIKE bsik-dmbtr,
      END OF ty_test.
    DATA: it_test TYPE STANDARD TABLE OF ty_test WITH HEADER LINE.
    SELECT SUM( a~dmbtr ) as dmbtr
    INTO CORRESPONDING FIELDS OF TABLE it_test
    FROM bsik AS a INNER JOIN faglflexa AS b ON ( a~bukrs = b~rbukrs AND a~gjahr = b~ryear AND a~belnr = b~docnr )
    WHERE a~bukrs = x_bukrs
    AND a~lifnr = p_lifnr
    AND a~shkzg = 'S'
    AND a~budat IN s_budat
    AND a~hkont GT '0000000000'
    AND a~hkont LE '9999999999'
    AND b~prctr = p_prctr.
    Please Reply if still any Issue,
    Best Regards,
    Faisal

  • SELECT SUM( field1 field2 ) INTO C1

    Is that possible with a select statement in ABAP or do I need to sum each row by itself then add them together afterwords?

    Hi Craig,
    this is not possible with a select statement in ABAP. You can use the routine mentioned by you:
    DATA: C1 TYPE i,
          C2 TYPE i,
          total type i.
    SELECT SUM( field1 ) SUM( fiedl2 ) into ( c1 c2 )from tablename.
    total = c1 + c2.
    Of course you can use the exec sql statement proposed by Andreas, but you have to select for the cllient explicitly. There are some disadvantages for native sql, too:
    1. platform dependent
    2. no syntax check for the native sql part
    3. you bypass the SAP database buffer
    For more details refer to the online help about EXEC SQL.
    Cheers,
    Morten

  • Select  sum(substr(8763,3,4)||'+'||9) from dual   how to add ?

    i want to add this substring value with 9
    select sum(substr(8763,3,4)||'+'||9) from dual
    means i need output 72

    FOR I IN C1 LOOP
    IF V_COUNT=0 THEN
    V_FILENAME:='AB'||P_DOCUMENT_NUM||'.txt';
    ELSE
    V_FILENAME:='AB'||SUBSTR(P_DOCUMENT_NUM,2,5)||+||V_COUNT||'.txt';
    END IF;
    L_FILE :=UTL_FILE.FOPEN('D:\oracle\visdb\9.2.0\plsql\temp',V_FILENAME,'W');
    UTL_FILE.PUT_LINE(L_FILE ,'E2|' || TRUNC(I.RAC_BILL_TO_CUSTOMER_NUM,0) ||l_attr||
    TRUNC(I.RAC_SHIP_TO_CUSTOMER_NUM,0) );
    V_COUNT:=V_COUNT+1;
    end loop;
    Actuelly i have write the data into different files names(i have to increase the filename for tranction) for each record of cursor
    but oracle is not allowing to add (V_FILENAME:='AB'||SUBSTR(P_DOCUMENT_NUM,2,5)||+||V_COUNT||'.txt';)
    that sum -----SUBSTR(P_DOCUMENT_NUM,2,5)||+||V_COUNT can any one help;

  • Selected fields not in order

    Hello All,
      I am selecting few fields from a table with the field in the condition 'rollname' = XXX.The rollname is a field in the table DD04t.If for exapmle in the selection screen if i give values like 'MATNR' 'EBELN' 'EBELP'  the select statment will select the fields in the sorted order.It is not in the same order as given in the selection screen.How to fetch this and display in the same order as given by the user in the selection screen.
    Thanks,
    Rakesh.

    You would have to somehow sort that data manually based on the data from the selection screen after the SELECT statement,  This could get quite messy.  For example, you would need a couple intermidate tables for 1) the select-option and 2) the output table.  Both would need to contain an index value.   You would sort the table by this value.
    Regards,
    Rich Heilman

  • Selection criteria are not applied to summary fields on group footers.

    I wonder if anyone can help me with this problem.  I am using Crystal reports version 11.2, and my data source is a Sql Server view.
    The records on the view have a date field, and I have selected all records within a given date range in "Selection Formulas".
    The records are then grouped, and the Crystal summary facility used to summarise number fields on the group footers.
    So for example, if my view contains four records, one with field "amount" = 2, one with field "amount" = 8, one with field "amount" = 6, one with field "amount" = 3, but only the first two records are within the valid date range, you would expect to see the first two records listed out at detail level, then field "amount" summarised at group level, with a summarised value of 10.
    ie ....                record1                      2
                           record2                      8   
                           group level total         10
    This works fine when I run the report using Crystal's "print preview" facility.  However, when the report is run from within an application written in C#.NET, the selection criteria are not applied to the summary field, so you get ..
                           record1                      2
                           record2                      8   
                           group level total          19
    I tried putting the date selection criteria at both record and group level, but that did not work.
    I googled the problem and found an article explaining that Crystal first performs the record-level selection, then it creates the groups and totals up any summary fields, and only then does it apply the group-level selection criteria, which can lead to problems like the one I have described above.  However, since I have put my date selection criteria at both record and group level, I do not understand why I still get the problem.
    In one report I got round this problem by creating a formula that returned zero if the record date was outside of the valid date range, and returned the number field to be summarised if the date was valid, then summarising that formula, instead of summarising the number field directly.
    In other reports I created one formula to set a shared variable as zero, then another formula to accumulate it at detail record level, then another formula to display the variable at the group footer.  In other words, I did not bother with the Crystal summary facility at all, but created my own summary facility.
    While googling the problem to see what other people did in this situation, I noticed that most fixes used variations of the "shared variables and formulae" fix to get round the problem.
    The problem is that I have lots of complex reports and it will take ages to replace the summarised fields with shared variables and formulae.  The reports were initially tested with "Print Preview" so we did not notice this problem until the C#.Net application was ready to use them.  And I can't believe that you are simply meant to ignore the summary facility and re-invent the wheel by doing it all manually.
    Please tell me that there is something simple that I have been doing wrong!!!  If I have not given enough information for you to answer, please let me know.
    Thanks,
    Anne-Marie

    Hi, Anne-Marie;
    You may be running into a common issue that is docuemented here:
    [SelectionFormula|https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes_boj/sdn_oss_boj_erq/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/scn_bosap/notes%7B6163636573733d36393736354636443646363436353344333933393338323636393736354637333631373036453646373436353733354636453735364436323635373233443330333033303331333233303334333833393335%7D.do]
    Regards,
    Jonathan
    Edited by: Jonathan Parminter on Mar 16, 2009 8:03 AM

  • Selection field not coming at Infopackage level

    Hi All,
    I am facing a strange problem.There is one field which is marked for selection at the datasource level.In the R/3 side we are getting that field as selection if we go for t-code RSA3.
    But in the BW system when we create an Info-package we do not get the same field under Data selection tab.We have tried to change the data type of that field and replicated the datasource but still it didnt worked.
    Please suggest on this issue as it a very high priority issue for us.
    Thanks in advance.
    Regards,
    Kshitij

    Hi Naveen,
    1) This is not a standard datasource.
    2) In RSA2 that field is marked for selection and it is showing for selection if we go for RSA3.
    3) Could you please elobrate more on what do you mean by 'attribute column'.???
    In R/3 system we have the same field for selection ( this field is related to 'no of days'=zdays[info object name]) but at Info package level in BW system it does not appear for selection.
    If you have time can we call you.Please pass on your number to me.
    Regards,
    Kshitij

  • Access the results of the following query in Java? SELECT sum(COL_X) FROM TABLE_A

    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery(
    "SELECT sum(COL_X) FROM TABLE_A");
    int = rset.getInt("sum(NUM_CUSTOMER)");This is obviously wrong. Could someone please help me a little on the syntax? I just want to be able to get the sum of the numeric values in a column without having to loop through a ResultSet and manually adding up the total. My question is how can I access the results of this query by assigning the sum to a java variable?

    Hi,
    Probably the easiest way is to use an alias for the sum column, i.e.:
    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery(
    "SELECT SUM(COL_X) MY_SUM FROM TABLE_A"
    int i = rset.getInt("MY_SUM");null

  • Selection screen fields are not getting detected in an infoset in code

    Hi All,
    I am developing an infoset query using logical database 'PNPCE'. I am facing problem while writing a validation on selection screen fields on an infoset query at infoset code level.
    The fields that are under program specific selection are determined at runtime with variables viz. SP$00001, SP$00002 etc. There are actually select options on selection screen of an infoset query.
    So I cannot write a direct  code on these fields as they do not exist at infoset level and hence cannot be detected.
    I want to put down a validation that if user does not select anything on selection-screen and executes the query, then he should get a pop-up message 'Narrow down your search...' and he should go back to selection screen again.
    Is there any alternative way to achieve this?

    hi,
    Your Screen resolution is more in the system that's why while creating it was fine and while executing it was gone after the next field.
    so you better create a frame and place that inside it or you can change cols size  in the properties about the columns you want

  • Select sum(distinct column ) from ....

    Hello All,
    I have a table the contains ID and size.
    An ID identifies a unique object, but it can be repeated. The following is valid:
    ID Size
    1 3
    4 5
    5 3
    1 3
    What I am trynig to do is get the sum of all sizes in the table. I tried this query:
    select sum(distinct size) from table;
    But it does give the right result since different objects could have the same size. I tried
    select sum(size) group by ID;
    But it prints to me huge number of IDs and sums the sizes of an ID together. What I want thuogh is to look at the unique rows (without duplicates) and then sum their sizes together and get the result.
    Any help would be greatly appreciated.
    Thank you
    P.S.: Sorry, I am an absolute Oracle/SQl newbie.
    Thanks for your help in advance

    An ID identifies a unique object, but it can be repeated.Fnord.
    I think your data model could withstand some refactoring but what you need to do is:
    SELECT sum(size) FROM
      (  SELECT distinct id, size FROM your_table)
    /This of course assumes that your duplication is complete and you don't have duplicate IDs with different sizes.
    You still ought to check out the concept of UNIQUE constraints though. A database ain't a database without relational integrity.
    Cheers, APC

  • Select List field in Form not pulling correct record

    I have a report that displays a Product Name and a Host Name. Each product can reside on multiple hosts and each host has multiple products, hence an associative table with product_host_asgmt_id, product_id and host_id is defined.
    The report I created selects data from the associative table and presents the user the product names and host names without a problem. the same report has an edit link that when selected will open a form that should display the selected host name and product name. In the form both of these fields are defined as Select List. The issue is that the list shows all the LOV but does not focus on the one that was selected in the report to edit.
    I unhid the product_host_asgmt_id, product_id and host_id in the form and the values contained are correct, so I think the Automated Row Fetch is working. This same form needs to be used for editing and for creating new values hence the Select List.
    I I have the Source section of the Host_name select list field set to : Only when current session state is null and the Source Type is an SQL query selecting all host_name form the host table.
    Any ideas how to get the values selected in the report to appear in the form?
    Thanks and apologize if this is trivial. I'm a rookie Apex user (but I like it).

    When you link to the form page, I assume you are passing the host_id value into a page item. Say you pass this value into item P2_HOST_ID, just make the select list item's Source Type Item (application or page item name) and enter P2_HOST_ID in the Source field.
    This assumes that the lov query is of the form "select host_name d, host_id r from ...".
    Be careful with Source Used "Only, ..." so that you never allow the page to display with a stale and unwanted value in P2_HOST_ID or that will produce an incorrect display value in the select list.
    Scott
    P.S. Please tell us your first name and put it into your handle and/or profile to help us.

Maybe you are looking for

  • Decl J2EE auth and auth with JAAS with custom module

    Hi Frank: I have posted another msg where I was trying the non-custom Login module with no luck. In the meantime, I tried the custom module and still having problem. When I click on dlmtest.jsp it brings up the inbuilt login module and not the custom

  • File Adapter. How to set file creation mode (ex. 666)?

    Hi All I'm using Outbound File Adapter to write files. Adapter creates the files whit access mode 622 (rw-r--r--). My requirement is to have files in 666 access mode. How can i achieve that? Thanks, Oleg.

  • Recommendations for DDR400

    Now that I have my machine booting with PC2100, I want to find some memory modules that will run at the max memory speed of the board.  I looked over the MSI recommended modules.  I need to run 1GB of RAM.  What type do you guys recommend? I have onl

  • Updated imac to OS X 10.8.5, now can't restart or shutdown

    Hi I applied the new 10.8.5 update this afternoon. As part of this it asks for a restart. Thing is it won't let me restart, logoff or shutdown now. Any advice on what the problem may be please? Thanks TinTin_57

  • How to auto-fill a book using only one master page

    I'm designing a rather simple photo book in Aperture.  I have a master page setup with six 2x3 image boxes per page.  Each image box has a metadata field for caption and for date/time.  I want to select a large number of images and auto-fill the book