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 Using a Method

This example demonstrates the construction of the group key using the assignment of return values.

Other versions: 7.31 | 7.40 | 7.54

Source Code

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

    DATA members LIKE flights.
    LOOP AT flights INTO DATA(wa)
         GROUP BY ( tz_from = get_time_zone( wa-airpfrom )
                    tz_to   = get_time_zone( wa-airpto )
                    size = GROUP SIZE index = GROUP INDEX )
         ASSIGNING FIELD-SYMBOL(<group>).
      out->write( name = `Group key`
                  data = <group> ).
      CLEAR members.
      LOOP AT GROUP <group> ASSIGNING FIELD-SYMBOL(<member>).
        members = VALUE #( BASE members ( <member> ) ).
      ENDLOOP.
      out->write( members )->line( ).
    ENDLOOP.

    out->display( ).

Description

Grouping of an internal table flights with group key binding. The group key of the group loop is constructed as a structure. The return values of the function method get_time_zone are assigned to the components tz_from and tz_to. The values of the columns airpfrom or airpto are passed to the input parameter of the method. This creates groups of rows that have the same combinations of time zones for the departure and destination airport.

In the simple case shown here, the table expression from the method could of course also be specified directly:

LOOP AT flights INTO DATA(wa)
     GROUP BY ( tz_from = airports[ id = wa-airpfrom ]-time_zone
                tz_to   = airports[ id = wa-airpto   ]-time_zone )
     ASSIGNING FIELD-SYMBOL(<group>).

Furthermore, the components size and index are created for the special language elements GROUP SIZE or GROUP INDEX to determine the size and index of each group.

The group key, bound to a field symbol <group>, and the additional components are produced in the group loop. In a member loop, the rows of each group are placed in an internal table members using the value operator with the addition BASE. These rows are then also displayed.

members could also be filled by evaluating a table comprehension using FOR ... IN GROUP, instead of in a member loop LOOP AT GROUP:

members = VALUE #( FOR <member> IN GROUP <group> ( <member> ) ).

The executable example for grouping with FOR demonstrates how the entire group loop can be implemented using expressions.