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 Function

This example demonstrates the construction of the group key using a string function.

Other versions: 7.31 | 7.40 | 7.54

Source Code

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

    out->begin_section( `Text` ).
    out->write( text ).
    out->next_section( `Grouping` ).
    DATA members LIKE text.
    LOOP AT text INTO DATA(line)
         GROUP BY replace( val = line regex = `\D` with = `` occ =  0 )
                  ASCENDING AS TEXT
                  ASSIGNING FIELD-SYMBOL(<group>).
      out->begin_section( |Group Key: { <group> }| ).
      CLEAR members.
      LOOP AT GROUP <group> ASSIGNING FIELD-SYMBOL(<member>).
        members = VALUE #( BASE members ( <member> ) ).
      ENDLOOP.
      out->write( members )->end_section( ).
    ENDLOOP.

    out->display( ).

Description

Grouping of an internal table text with group key binding. The group key of the group loop is constructed as a value of the type string. This value is calculated from the content of each table row using the predefined function replace. Groups of rows are then created that contain the same digits in the same order in their text. The groups are sorted in ascending order according to the group key.

The group key, bound to a field symbol <group>, is produced in the group loop. The first group key is an initial text string. 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 <member> IN GROUP <group> ( <member> ) ).

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