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 Column Values

This example demonstrates the construction of the group key using simple value assignments.

Other versions: 7.31 | 7.40 | 7.54

Source Code

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

    out->begin_section( `Flights` ).
    out->write( flights ).
    out->begin_section( `Grouping` ).
    DATA members LIKE flights.
    LOOP AT flights INTO DATA(flight)
         GROUP BY ( carrier = flight-carrid cityfr = flight-cityfrom
                    size = GROUP SIZE index = GROUP INDEX )
                  ASCENDING
                  REFERENCE INTO DATA(group_ref).
      out->begin_section(
        |Group Key: { group_ref->carrier }, { group_ref->cityfr }| ).
      out->write(
        |Group Size: {  group_ref->size  }, | &&
        |Group Index: { group_ref->index }| ).
      CLEAR members.
      LOOP AT GROUP group_ref ASSIGNING FIELD-SYMBOL(<flight>).
        members = VALUE #( BASE members ( <flight> ) ).
      ENDLOOP.
      out->write( members )->end_section( ).
    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. Here, the values of the columns carrid or cityfrom in each row of the internal table are assigned to the components carrier and cityfr. This creates groups of rows that have the same value in these columns. 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 reference variable group_ref, 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 the evaluation of a table comprehension sing FOR ... IN GROUP, instead of in a member loop LOOP AT GROUP:

members = VALUE #( FOR <flight> IN GROUP group_ref ( <flight> ) ).

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