SUM - Control Level Processing for Internal Tables

Basic form

SUM.

Effect

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 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:

TYPES: BEGIN OF T_TYPE,
         CODE(4),
         SALES    TYPE P,
         DISCOUNT TYPE P,
       END OF T_TYPE.

DATA: T TYPE STANDARD TABLE OF T_TYPE WITH NON-UNIQUE
             DEFAULT KEY INITIAL SIZE 100,
      WA_T TYPE T_TYPE.
...
LOOP AT T INTO WA_T.
  AT FIRST.
    SUM.
    WRITE: /4 'Grand Total:',
            20 WA_T-SALES, 40 WA_T-DISCOUNT.
    ULINE. SKIP.
  ENDAT.
  WRITE: / WA_T-CODE,
          20 WA_T-SALES, 40 WA_T-DISCOUNT.
  AT END OF CODE.
    SUM.
    WRITE: / WA_T-CODE, 10 'Total:',
            20 WA_T-SALES, 40 WA_T-DISCOUNT.
    SKIP.
  ENDAT.
ENDLOOP.

Notes

  1. 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.

  2. You cannot use the SUM statement in a loop starting with "LOOP ... ASSIGNING <fs>", since the table lines are directly accessed through the field symbol <fs> and therefore no work area is available for calculating the total.

  3. When you apply LOOP to a sorted extract (SORT), the field SUM(f) contains the control total of f at the end of the control group - if f is a field of type I, F or P.


Exceptions

Catchable Exceptions

CX_SY_ARITHMETIC_OVERFLOW

Non-Catchable Exceptions

Additional help

Processing Table Lines in Loops