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 in Packages

This example demonstrates a construction of the group key that does not depend on the row content.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    DATA out TYPE REF TO if_demo_output.

    cl_demo_input=>request( EXPORTING text  = `Package size`
                            CHANGING  field = n ).
    IF n <= 0.
      RETURN.
    ENDIF.

    out = REDUCE #(
      INIT o = cl_demo_output=>new(
                 )->begin_section( |Packages of { n }| )
      FOR GROUPS OF wa IN itab GROUP BY group( )
      LET group = VALUE i_tab( FOR <wa> IN GROUP wa ( <wa> ) ) IN
      NEXT o = o->write( group ) ).

    out->display( ).

Description

This example works in the same way as the corresponding example for LOOP AT ... GROUP BY, but uses the expression FOR GROUPS ... OF for a table reduction with REDUCE instead of the group loop.The group key after GROUP BY cannot be constructed in the same way in this case, since the system field sy-tabix is not available during grouping in expressions. The addition INDEX INTO cannot be used either, since it sets a value for each group but not for each evaluated row. This is why a self-defined method, group, is called here to count the rows.

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 example for LOOP AT ... GROUP BY instead of the member loop.