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 Comparison

This example demonstrates the construction of the group key using comparison expressions.

Other versions: 7.31 | 7.40 | 7.54

Source Code

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

    DATA(threshold) = 5.
    cl_demo_input=>request( CHANGING field = threshold ).

    out->begin_section( `Grouping` ).
    DATA members LIKE numbers.
    LOOP AT numbers INTO DATA(number)
         GROUP BY COND string(
           WHEN number <= threshold THEN |LE { threshold }|
                                   ELSE |GT { threshold }| )
         ASSIGNING FIELD-SYMBOL(<group>).
      out->begin_section( <group> ).
      CLEAR members.
      LOOP AT GROUP <group> REFERENCE INTO DATA(member_ref).
        members = VALUE #( BASE members ( member_ref->* ) ).
      ENDLOOP.
      out->write( members )->end_section( ).
    ENDLOOP.
    out->display( ).

Description

Grouping of an internal table numbers 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 conditional operator cond. This creates groups of rows whose content is either less than or equal to or greater than an entered value.

The group key, bound to a field symbol <group>, is 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 <member> IN GROUP <group> ( <member> ) ).

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