Skip to content

ABAP Keyword Documentation →  ABAP - Reference →  Processing Internal Data →  Internal Tables →  Processing Statements for Internal Tables →  LOOP AT itab →  LOOP AT itab - GROUP BY →  Examples of Grouping with LOOP 

Internal Tables, Grouping with LOOP for Aggregates

This example demonstrates a grouping with aggregates.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    initialize( ).

    DATA(out) = cl_demo_output=>new( ).

    DATA:
      BEGIN OF aggregate,
        sum TYPE i,
        max TYPE i,
        min TYPE i,
        avg TYPE decfloat34,
      END OF aggregate.

    out->next_section( `Table`
      )->write( numbers ).

    LOOP AT numbers ASSIGNING FIELD-SYMBOL(<wa>)
         GROUP BY ( key = <wa>-key  count = GROUP SIZE )
         ASCENDING
         ASSIGNING FIELD-SYMBOL(<group_key>).

      out->next_section( |Group Key: { <group_key>-key }| ).
      aggregate = VALUE #( min = 101 ).
      DATA(members) = VALUE itab( ).
      LOOP AT GROUP <group_key> ASSIGNING FIELD-SYMBOL(<member>).
        members = VALUE #( BASE members ( <member> ) ).
        aggregate-sum = aggregate-sum + <member>-num.
        aggregate-max = nmax( val1 = aggregate-max
                              val2 = <member>-num ).
        aggregate-min = nmin( val1 = aggregate-min
                              val2 = <member>-num ).
      ENDLOOP.
      aggregate-avg = aggregate-sum / <group_key>-count.
      SORT members BY num DESCENDING.
      out->write( members
        )->write( aggregate ).
    ENDLOOP.
    out->display( ).

Description

A group loop across an internal table numbers is used to group by the content of the column key. For the groups, the usual SQL aggregates sum, maximum, minimum, and average are calculated for the second column num. The output is the group members and the associated aggregates. The example enables a maximum number of different key values and rows in the internal table to be entered. The values in the second column are random numbers between 1 and 100.

The example above demonstrates an implementation with a member loop. A further example shows how the member loop can be replaced by table comprehensions and table reductions while preserving the function. Another example demonstrates how the entire group loop can be implemented using expressions.