Using SUM BY to limit result of 3 union queries (11g)

Hey guys,
First time posting here (btw, I've tried changing my handle name via edit profile here to no success! Ugh!).
I need to modify a report that's built off of 3 union queries.  Here's a simplified table version of the union result:
Label
Year
Category
Score
Ct
A
2005
1a
4.0
1
A
2005
2b
3.5
1
A
2005
3c
2.5
1
B
2006
1a
2.8
1
B
2006
2b
4.0
1
Ct is a calculated item where I did a CASE on a field just to get a count of 1 on this column.  I need to limit this result where per label, per year, there are 3 categories.  So, looking at above table, Label A rows will be the only set returned.  To "hopefully" get 3 under the Ct column where there are 3 categories per year, per label, I have tried "SUM(Ct by Year)" but it didn't give the correct result.  I have also tried "SUM(SUM(Ct by Year) by Label)" and that didn't work either (not that I expected it to work).  I also messed around with GROUP BY to no success either.
Has anyone run into something like this?  Any input/tip is appreciated. THANKS!!
Twiggy99

Are you using outer query to get the same?
btw: What is when you use count instead of sum?

Similar Messages

  • Best way to limit results from a query.

    I need to limit the number of results returned from the database to the first x rows. What I need is a database independant way to achieve this - i.e. I can't use LIMIT, TOP, etc. in my query.
    My question therefore is does statment.setMaxRows(x) restrict my results at the database level or my application's view to the database? I.e. will the complete SELECT * run within the database but the first x will be returned to the resultset, which could be quite a performance drain at db level. Or will this have the same effect as running a query SELECT TOP X FROM... which will be a much quicker query to run?
    Any help greatly appreciated!

    The best, and only fool proof way to limit results (rows, columns) from a query, and not waste database resources is to code your query so it only returns the rows and columns that you need. That might mean providing date ranges, sequence number ranges and all other WHERE criteria that can be used to filter the data to exactly what you need.
    There are ways to limit what is available to your Java program, but in most cases, the entire SQL must be completed before any results can be returned. The simplest example is; using the SORT command to get the data into the order you require, will first require that all rows be made available to the sort. The fact that you only want the top 5 rows doesn't matter to the DBMS because it cannot give them to you incrementally.
    Focus on getting your SQL as efficient as possible. If the SQL runs efficiently, you can use almost any of the JDBC commands to limit, list, cursor forward and backward, etc, without regard to their overhead.

  • Problem using SUM standard function  during Field Mapping

    Hi Experts ,
    I am trying to sum all LIFMG 's in in the lineitems of a particular
    header and map this result to Lifmg of the header.(Idoc with multiple headers and line item).I am using SUM standard function.
    Rough Source structure.
    Header1
          vbeln
    ....Lineitem1
          vbeln
          posnr
    ......LIFMG
    ....Lineitem2
            vbeln
            posnr
    ......LIFMG
    Header2
         vbeln
    ....Lineitem1
            vbeln
           posnr
    ......LIFMG
    ....Lineitem2
            vbeln
           posnr
    ......LIFMG
    I am able to find the SUM ...but in the target structure's Header field  I am getting
    repeated value of the corresponding sum in each header ...i.e.
    Header1
    LFIMG-- 100
    LFIMG    100
    Header2
    LFIMG-- 102
    LFIMG    102
    How to get a single value for each .
    Regards,
    Deepak

    Solved Myself ...
    Placed  sum after  if without else ...
    placing it before was causing ...those values to be replicated.

  • In VB how do I pass my low and high limit results from a TestStand Step into the ResultList and how do I retrieve them from the same?

    I am retrieving high and low limits from step results in VB code that looks something like this:
    ' (This occurs while processing a UIMsg_Trace event)
    Set step = context.Sequence.GetStep(previousStepIndex, context.StepGroup)
    '(etc.)
    ' Get step limits for results
    Set oStepProperty = step.AsPropertyObject
    If oStepProperty.Exists("limits", 0&) Then
    dblLimitHigh = step.limits.high
    dblLimitLow = step.limits.low
    '(etc.)
    So far, so good. I can see these results in
    VB debug mode.
    Immediately after this is where I try to put the limits into the results list:
    'Add Limits to results
    call mCurrentExecution.AddExtraResult("Step.Limits.High", "UpperLimit")
    call mCurrentExecution.AddExtraResult("Step.Limits.Low", "LowerLimit")
    (No apparent errors here while executing)
    But in another section of code when I try to extract the limits, I get some of the results, but I do not get any limits results.
    That section of code occurs while processing a UIMsg_EndExecution event and looks something like this:
    (misc declarations)
    'Get the size of the ResultList array
    Call oResultList.GetDimensions("", 0, sDummy, sDummy, iElements, eType)
    'Step through the ResultList array
    For iItem = 0 To iElements - 1
    Dim oResult As PropertyObject
    Set oResult = oResultList.GetPropertyObject("[" & CStr(iItem) & "]", 0)
    sMsg = "StepName = " & oResult.GetValString("TS.StepName", 0) & _
    ", Status = " & oResult.GetValString("Status", 0)
    If oResult.Exists("limits", 0&) Then
    Debug.Print "HighLimit: " & CStr(oResult.GetValNumber("Step.Limits.High", 0))
    Debug.Print "LowLimit: " & CStr(oResult.GetValNumber("Step.Limits.Low", 0))
    End If
    '(handle the results)
    Next iItem
    I can get the step name, I can get the status, but I can't get the limits. The "if" statement above which checks for "limits" never becomes true, because, apparently the limit results never made it to the results array.
    So, my question again is how can I pass the low and high limit results to the results list, and how can I retrieve the same from the results list?
    Thanks,
    Griff

    Griff,
    Hmmmm...
    I use this feature all the time and it works for me. The only real
    difference between the code you posted and what I do is that I don't
    retrieve a property object for each TestStand object, instead I pass the
    entire sequence context (of the process model) then retrieve a property
    object for the entire sequence context and use the full TestStand object
    path to reference sub-properties. For example, to access a step's
    ResultList property called "foo" I would use the path:
    "Locals.ResultList[0].TS.SequenceCall.ResultList[].Foo"
    My guess is the problem has something to do with the object from which
    you're retrieving the property object and/or the path used to obtain
    sub-properties from the object. You should be able to break-point in the
    TestStand sequence editor immediately after the test step in question
    executes, then see the extra results in the step's ResultList using the
    context viewer.
    For example, see the attached sequence file. The first step adds the extra
    result "Step.Limits" as "Limits", the second step is a Numeric Limit (which
    will have the step property of "Limits") test and the third step pops up a
    dialog if the Limits property is found in the Numeric Limit test's
    ResultList. In the Sequence Editor, try executing with the first step
    enalbled then again with the first step skipped and breakpoint on the third
    step. Use the context viewer to observe where the Limits property is added.
    That might help you narrow in on how to specify the property path to
    retrieve the value.
    If in your code, you see the extra results in the context viewer, then the
    problem lies in how you're trying to retrieve the property. If the extra
    results aren't there, then something is wrong in how you're specifying them,
    most likely a problem with the AddExtraResult call itself.
    One other thing to check... its hard to tell from the code you posted... but
    make sure you're calling AddExtraResult on the correct execution object and
    that you're calling AddExtraResult ~before~ executing the step you want the
    result to show up for. Another programmer here made the mistake of assuming
    he could call AddExtraResult ~after~ the step executed and TestStand would
    "back fill" previously executed steps. Thats not the case. Also, another
    mistake he made was expecting the extra results to appear for steps that did
    not contain the original step properties. For example, a string comparison
    step doesn't have a "Step.Limits.High" property, so if this property is
    called out explicitly in AddExtraResult, then the extra result won't appear
    in the string comparison's ResultList entry. Thats why you should simply
    specify "Step.Limits" to AddExtraResul so the Limits container (whose
    contents vary depending on the step type) will get copied to the ResultList
    regardless of the step type.
    I call AddExtraResult at the beginning of my process model, not in a UI
    message handler, so there may be some gotcha from calling it that way. If
    all else fails, try adding the AddExtraResult near the beginning of your
    process model and see if the extra results appear in each step's ResultList.
    Good luck,
    Bob Rafuse
    Etec Inc.
    [Attachment DebugExtraResults.seq, see below]
    Attachments:
    DebugExtraResults.seq ‏20 KB

  • How do I use Airport Extreme to limit internet time for my kids?  His computer is hardwired to the modem.

    How do I use Airport Extreme to limit internet time for my kids?  His computer is hardwired to the modem.

    You can set up daily time limits for each computer that connects using wireless, but it is not possible to do this when a computer is connecting directly using a wired Ethernet connection.
    Open Macintosh HD > Applications > Utilities > AirPort Utility on your Mac and click Manual Setup
    Click the Access Control tab below the icons
    Select Timed Access
    For more details on this, click the Help menu at the top of the screen and enter the following phrase into the search box:
    Controlling access to your wireless network
    A more sophisticated approach would be to use a service provided by OpenDNS. From your computer, this would allow you to monitor web sites visited, and block any unsuitable sites. More info is here:
    http://www.opendns.com/landings/familyshield

  • USING SUM IN INTERNAL TABLE

    plz give me a simple example for using SUM in internal table and do some calculations in the same internal table.

    HI
    CHECK WITH THIS
    Syntax
    SUM.
    Effect
    The statement SUM can only be specified within a loop starting with LOOP, and is only considered within a AT- ENDAT control structure. Prerequisites for using the statement SUM include using the addition INTO in the LOOP statement, and that the specified work area wa is compatible with the row type of the internal table. In addition, SUM cannot be used when the row type of the internal table itab contains components that are tables.
    The statement SUM calculates the component total with the numeric data type (i, p, f) of all rows in the current control level and assigns these to the components of the work area wa. In the control levels FIRST, LAST, and outside of an AT-ENDAT control structure, the system calculates the sum of numeric components of all rows in the internal table.
    Example
    Control level processing for creating a list. At the end of line groups, the total of reserved places is calculated and issued.
    DATA: sflight_tab TYPE SORTED TABLE OF sflight
                      WITH UNIQUE KEY carrid connid fldate,
          sflight_wa  LIKE LINE OF sflight_tab.
    SELECT *
           FROM sflight
           INTO TABLE sflight_tab.
    LOOP AT sflight_tab INTO sflight_wa.
      AT NEW connid.
        WRITE: / sflight_wa-carrid,
                 sflight_wa-connid.
        ULINE.
      ENDAT.
      WRITE: / sflight_wa-fldate,
               sflight_wa-seatsocc.
      AT END OF connid.
        SUM.
        ULINE.
        WRITE: / 'Sum',
                  sflight_wa-seatsocc UNDER sflight_wa-seatsocc.
        SKIP.
      ENDAT.
      AT END OF carrid.
        SUM.
        ULINE.
        WRITE: / 'Carrier Sum',
                  sflight_wa-seatsocc UNDER sflight_wa-seatsocc.
        NEW-PAGE.
      ENDAT.
      AT LAST.
        SUM.
        WRITE: / 'Overall Sum',
                  sflight_wa-seatsocc UNDER sflight_wa-seatsocc.
      ENDAT.
    ENDLOOP.
    Hope this solves ur problem....
    <b>do reward if useful....</b>
    regards
    dinesh

  • Using sum function and round function in single text form field

    Hi all,
    I have a column Name - A . In the rtf template i have summed up the column A and showing it. But the output is coming as 99.9999997. I want to round it to 100.
    I tried using <?round(sum(A),2)?> but dint workout.
    I also tried using variables. It is also not working.. I used <?xdoxslt:set_variable($_XDOCTX,’ABS',sum(A)?> and then i used get variable to get it.... But it throwing error while using sum in the set variable step.
    Can anyone please help me..
    Thanks
    Sunil

    Hi Sunil,
    Calculate the sum into a Variable. and apply round function on the variable to get the desired value.
    Calculating sum:
    <?xdoxslt:set_variable($_XDOCTX,'v',xdoxslt:get_variable($_XDOCTX,'v')+DOLLARS)?> (its running sum formula,should be placed inside the table to get sum of all rows of particular column)
    here Variable 'v' holds the sum value
    apply round function:
    <?round(xdoxslt:get_variable($_XDOCTX,'v'))?>
    Thanks and Regards,
    Aravind

  • When using Quite Imposing Plus the resulting file is only given a Temp name which will be sent as the document name.

    Our company has recently upgraded form Acrobat Professional 8 to Acrobat professional XI. We also use the Quite Imposing Plus plug-in in both versions. Now when using Quite Imposing Plus the resulting file is only given a Temp name which will be sent as the document name to the printer unless the imposed document is first saved. This was not the case in Acrobat Professional 8. I have attached a screen shots that shows an example.
    Is there any reason why this is happening and how can we stop it.

    Thank you for your advice although I think you may be incorrect as the naming of the documents made with Quite Imposing is correct in Acrobat 8.
    After reading the comment below it would seem something has changed from version nine onwards.
    Going forward we plan on changing the way we save and send our imposed documents to print but thank you for your time.

  • When "Use Google Instant", "Open search results in a new browser window." does not function.

    In the "Google Search Setting", if select "Do not use Google Instant", then the selected search result of Google Search will be displayed in a new window, but if "Use Google Instant", the selected result will replace Google Search window. This problem does not exist when using Chrome Browser.

    That does what it says - even if Google tells the browser to open the page in a new window, you have told Firefox to ignore that and open it in a new tab. Uncheck the box and you should get the result you want.

  • How can i use SUM aggregate in select query?

    HI,
    GURUS,
    How can i use SUM function in Select Query and i want to store that value into itab.
    for ex:
    TABLES: vbap.
    types: begin of ty_vbap,
           incluse type vbap,
           sum type string,
          end of ty_vbap.
    data: i_vbap type TABLE OF ty_vbap,
          w_vbap type ty_vbap.
    SELECT sum(posnr) FROM vbap into table i_vbap up to 5 rows.
                            (or)
    SELECT sum(posnr) FROM vbap into table i_vbap group by vbeln.
      loop at i_vbap into w_vbap
    " which variable have to use to display summed value.
      endloop.
    if above code is not understandable pleas give ome sample code on  above query.
    Thank u,
    shabeer ahmed.

    Hi,
    Check this sample code.
    TABLES SBOOK.
    DATA:  COUNT TYPE I, SUM TYPE P DECIMALS 2, AVG TYPE F.
    DATA:  CONNID LIKE SBOOK-CONNID.
    SELECT CONNID COUNT( * ) SUM( LUGGWEIGHT ) AVG( LUGGWEIGHT )
           INTO (CONNID, COUNT, SUM, AVG)
           FROM SBOOK
           WHERE
             CARRID   = 'LH '      AND
             FLDATE   = '19950228'
           GROUP BY CONNID.
      WRITE: / CONNID, COUNT, SUM, AVG.
    ENDSELECT.
    Regards,
    Sravanthi

  • Using Sum Function in Oracle(on 24 th)

    Hi all i wrote the following query.
    SELECT RESPONSER_ID,SUM(SUM(DISTINCT WORK_SPACE)) AS SCORE,COUNT(DISTINCT QUESTION_ID) AS QCOUNT FROM TQDB_LEARNER_RESPONSE WHERE RESPONSER_ID=328
    GROUP BY RESPONSER_ID
    I am getting the following error.
    ORA-00937: not a single-group group function
    Any body Pls help me.

    why use sum(sum()
    SUM(SUM(DISTINCT WORK_SPACE)) AS SCORE,
    SELECT
         RESPONSER_ID,
         SUM(DISTINCT WORK_SPACE) AS SCORE,
         COUNT(DISTINCT QUESTION_ID) AS QCOUNT
    FROM
         TQDB_LEARNER_RESPONSE
    WHERE
         RESPONSER_ID=328
    GROUP BY
         RESPONSER_ID Regards
    Singh

  • How can I use SUM function to calculate # of employees in the comp.&deptnt?

    I've got two tables: employee & department. I am trying to calculate total employees by department and total employees by the entire company. I know I need to use SUM function, but I only can calculate total employees by department & by company separately. I need to get this output:
    DEPT_NAME     DEPT_TOTAL_SALARY         COMPANY_TOTAL_SALARY
    RESEARCH                  10875                        29025
    SALES                      9400                        29025   
    ACCOUNTING                 8750                        29025     
    This is my code:
    SELECT department_name, SUM(salary) as total_salary
    FROM employee, department
    WHERE employee.department_id = department.department_id
    GROUP BY department_name;
    SELECT SUM(salary)
    FROM employee;
    Can somebody help please?
    Thank you in advance.Edited by: user13675672 on Jan 30, 2011 2:29 PM
    Edited by: user13675672 on Jan 30, 2011 2:31 PM

    Hi, Peter
    Peter Gjelstrup wrote:
    ... There might be a smarter way, with no re-select.You're right, as usual.
    SELECT       d.dname
    ,       SUM (e.sal)               AS dept_tot_sal
    ,       SUM (SUM (e.sal)) OVER ()     AS comp_tot_sal
    FROM       scott.dept     d
    JOIN       scott.emp     e  ON     d.deptno     = e.deptno
    GROUP BY  d.dname
    ;Analytic functions are computed after aggregate functions, so an aggregate function can be nested inside an analytic function.
    Another way (without a sub-query, at least) would be SELECT DISTINCT, with only analytic functions.
    SELECT DISTINCT
           d.dname
    ,       SUM (e.sal) OVER (PARTITION BY  d.dname)     AS dept_tot_sal
    ,       SUM (e.sal) OVER ()                    AS comp_tot_sal
    FROM       scott.dept     d
    JOIN       scott.emp     e  ON     d.deptno     = e.deptno
    ;

  • Shadow Instance Left Behind in SLD After Using SUM

    Hello,
    Is there a standard procedure for removing the SLD information left behind by the creation of shadow ABAP instances when using SUM to update or upgrade systems? Should SUM have some final step for this built in, or should the update instructions include a step to go into SLD and delete the shadow instance information manually?
    My situation is as follows. I recently updated the support package stack for my Solution Manager 7.1 system from sps4 to sps12 using SUM (this was for a new installation of Solution Manager). Afterwards, I used SOLMAN_SETUP to perform the System Preparation and Basic Configuration steps, and now I have progressed to Managed System Configuration. The first managed system to configure is Solution Manager itself, and in working on the SolMan ABAP instance, in step 6, 'Enter Landscape Parameters,' I noticed that there is an extra ABAP instance, DVEBMGS03, showing up as a landscape object node. I was puzzled for a bit about this, as there is no instance 03 in my SolMan system, only 00, 01, and 02. Eventually I figured out that SOLMAN_SETUP gets this landscape information from the obvious place, LMDB, which in turn gets it from SLD, and sure enough in LMDB and SLD I can find the "AppServer 03" instance defined.
    That's when the light bulb hit. SUM creates a shadow ABAP instance when updating the support package stack (unlike using SPAM), similar to as it does during an upgrade. It deletes the shadow instance at the end of the update, but in the meantime the system has synchronized itself to SLD, and now SLD has a definition for that shadow instance that doesn't go away when the instance is deleted.
    It's easy enough to manually delete it in SLD, of course, but that leads me to wonder if there's a preferred option for handling this other than manual manipulation of SLD data.
    The version of SUM I used was 1.0 sp11 pl9.
    Regards,
    Matt

    That's right, although for a support pack update, I'm not sure if the jobs even get suspended. In the past, when doing this with SPAM, there was no shadow instance to worry about, so it wasn't an issue. In upgrades, when there typically is a shadow instance, things are much more "shut down" in the system (jobs suspended, etc) than is often the case with support pack updates (though perhaps those should be just as much "shut down").
    So in future I will definitely keep an eye out for it. Stopping the data supplier should be added to the tool and/or listed as a manual step in the guide to prevent inconsistent landscape and software component data from being replicated (or perhaps it already is and I missed it). I'm going to tag Boris Rubarth to get his take on it, as he is a key player in the development and maintenance of the SUM tool.
    Deleting the extra instance in SLD was very easy, and I watched it replicate to LMDB very quickly, and it immediately disappeared upon refresh from the managed system configuration tool. However, it later showed up in diagnostics agent administration, as well, as a warning about a system path not being reachable by the agent (it was trying to reach \usr\sap\SID\DVEBMGS03, which doesn't exist), and so I had to edit the agent landscape paths to remove that as well).
    Although the problem is long since solved in my system, as described above, I will keep the question open for a few more hours to see what Boris or others may have to add.
    Regards,
    Matt

  • Error in stack.xml - Upgrade to EHP1 SPS 8 using SUM

    Hello
    we're currently upgrading our PI-system. We use SUM
    as upgrade tool.
    I've opened a maintenance task in solution manager and defined the
    target support package stack (SAP PI 7.1 EHP 1 SPS8).
    During the upgrade procedure (step 2: Select Target) in SUM I get an
    error, after selecting the stack xml file:
    Cannot construct a support package stack from
    file /usr/sap/trans/EHPinstfiles/SMSDXML_XIT_20111010063232.419.xml.
    Stack definition
    file /usr/sap/trans/EHPinstfiles/SMSDXML_XIT_20111010063232.419.xml is
    rejected.
    See error messages in /usr/sap/XIT/SUM/sdt/log/SUM/DEFINE-TARGET-
    SOURCE_09.LOG.
    DETECT  define_target  define-target-dialog  define-target-
    source  com.sap.sdt.j2ee.services.servicesimpl.DefineTargetService  class com.sap.sdt.j2ee.tools.spxmlparser.SPXmlParserException
    Next an outtake of the log-file:
    Oct 12, 2011 10:31:41 AM [Info  ]: Basic component properties of SDU file DEPLOYARCHIVES/sap.com~tc~lm~itsam~co~ui~xi~msg~wd.ear have been read. Component name is sap.com/tc/lm/itsam/co/ui/xi/msg/wd and version is 7.11.
    Oct 12, 2011 10:31:41 AM [Info  ]: Subcomponents of component sap.com/SOAMONBASIC have been processed.
    Oct 12, 2011 10:31:41 AM [Info  ]: File /usr/sap/trans/EHPinstfiles/SOAMONBASIC08_0-10006070.SCA has been analyzed for deployment components.
    Oct 12, 2011 10:31:41 AM [Error ]: Component with name SERVERCORE and vendor sap.com has multiple archive names.
    Oct 12, 2011 10:31:41 AM [Info  ]: Parsing of stack definition file /usr/sap/trans/EHPinstfiles/SMSDXML_XIT_20111010063232.419.xml has finished.
    Oct 12, 2011 10:31:41 AM [Error ]: The following problem has occurred during step execution com.sap.sdt.j2ee.tools.spxmlparser.SPXmlParserException: Cannot construct a support package
    stack from file /usr/sap/trans/EHPinstfiles/SMSDXML_XIT_20111010063232.419.xml.
    Stack definition file /usr/sap/trans/EHPinstfiles/SMSDXML_XIT_20111010063232.419.xml is rejected. See error messages in /usr/sap/XIT/SUM/sdt/log/SUM/DEFINE-TARGET-SOURCE_12.LOG.
    Regards
    Christian Kaiser

    Hello
    I've solved the problem.
    In the stack.xml file are multiples software-components with the same name, here "SERVERCORE".
    I had 3 entries, two with patch-level 0 and one with patch-level 1.
    I've deleted the two entries with patch-level 0 and then it works.
    Regards Christian

  • Problem using SUM BY

    I need to count the number of jobs by year and nature of the job.
    I need to calculate also the number only by year (to calculate, later, the percentage). To do this, I tried to use the SUM BY statement:
    SUM("- Misure"."Numero Lavori" by "- Inizio Lavoro"."Anno Inizio Lavoro")
    Note that the number of jobs is calculated with the COUNT DISTINCT aggregation rule.
    Here's the query generated by BI:
    WITH
    SAWITH0 AS (select count(distinct T6686.CD_LAVORO) as c1,
    T6906.ANNO as c2,
    T6842.CD_RITORNO_LAVORO as c3
    from
    L_RITORNO_LAVORO T6842,
    L_DATA T6906 /* L_DATA_INIZIO_LAVORO */ ,
    F_LAVORO T6686
    where ( T6686.ID_RITORNO_LAVORO = T6842.ID_RITORNO_LAVORO and T6686.ID_DT_INIZIO_LAVORO = T6906.ID_DATA )
    group by T6842.CD_RITORNO_LAVORO, T6906.ANNO),
    SAWITH1 AS (select sum(SAWITH0.c1) as c1,
    SAWITH0.c2 as c2,
    SAWITH0.c3 as c3,
    SAWITH0.c1 as c4
    from
    SAWITH0
    group by SAWITH0.c1, SAWITH0.c2, SAWITH0.c3)
    select distinct SAWITH1.c2 as c1,
    SAWITH1.c3 as c2,
    SAWITH1.c4 as c3,
    SAWITH1.c1 as c4
    from
    SAWITH1
    I suspect the part painted in bold shouldn't be there. Anyone can help me?

    hi,,,,,,
    When processing an internal table in a block starting with LOOP and concluded by ENDLOOP , SUM calculates the control totals of all fields of type I , F and P (see also ABAP/4 number types ) and places them in the LOOP output area (header line of the internal table or an explicitly specified work area).
    You can use the SUM statement both at the end and the beginning of a control group (see also AT FIRST/LAST ).
    Example
    Display the table T with sub-totals:
    DATA: BEGIN OF T OCCURS 100,
    CODE(4),
    SALES TYPE P,
    DISCOUNT TYPE P,
    END OF T.
    LOOP AT T.
    AT FIRST.
    SUM.
    WRITE: /4 'Grand Total:',
    20 T-SALES, 40 T-DISCOUNT.
    ULINE. SKIP.
    ENDAT.
    WRITE: / T-CODE,
    20 T-SALES, 40 T-DISCOUNT.
    AT END OF CODE.
    SUM.
    WRITE: / T-CODE, 10 'Total:',
    20 T-SALES, 40 T-DISCOUNT.
    SKIP.
    ENDAT.
    ENDLOOP.
    Notes
    When you use SUM in a LOOP with an explicitly specified output area, this output area must be compatible with the line type of the internal table.
    When using LOOP to process a sorted extract (see SORT ), the control total of f at the end of the group appears in the field SUM(f) - - if f is type I , F or P .
    Thanks
    Saurabh

Maybe you are looking for