Skip to content

ABAP Keyword Documentation →  ABAP − Reference →  Processing Internal Data →  Internal Tables →  Expressions and Functions for Internal Tables →  FOR - Table Iterations →  Examples of Grouping with FOR 

Internal Tables, Grouping with FOR 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 TYPE REF TO if_demo_output.

    out = REDUCE #(
      INIT o = cl_demo_output=>new(
                 )->begin_section( `Text`
                 )->write( text
                 )->next_section( `Grouping` )
      FOR GROUPS <GROUP> OF LINE IN TEXT
            GROUP BY REPLACE(
                       val = LINE REGEX = `\D` WITH = `` occ =  0 )
            ASCENDING AS TEXT
      LET members = VALUE text_tab(
                      FOR <member> IN GROUP <group> ( <member> ) ) IN
      NEXT o = o->begin_section( |Group Key: { <group> }|
               )->write( members )->end_section( ) ).

    out->display( ).

Description

This example works in the same way as the corresponding executable example for LOOP AT ... GROUP BY, but uses the expression FOR GROUPS ... OF for a table reduction with REDUCE instead of the group loop. In both cases, the group key after GROUP BY is constructed in exactly the same way.

The result of the table reduction is a reference to an object of the class CL_DEMO_OUTPUT to which the results of the grouping are written. The group members are written to a local auxiliary table members using a table comprehension with VALUE. This table comprehension could also be used in the executable example for LOOP AT ... GROUP BY instead of the member loop.