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 Overlaps

This example demonstrates the construction of the group key if conditions overlap.

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( `LE 5, BT 3 AND 7, GT 5` )
      FOR GROUPS <group> OF wa IN itab
            GROUP BY COND string( WHEN wa <= 5 THEN `LE 5`
                                 WHEN wa BETWEEN 3 AND 7
                                              THEN `BT 3 AND 7`
                                 WHEN wa >  5 THEN `GT 5` )
      LET members = VALUE i_tab(
                      FOR <member> IN GROUP <group> ( <member> ) ) IN
      NEXT o = o->begin_section( <group>
               )->write( members )->end_section( ) ).


    out = REDUCE #(
      INIT o = out->next_section( `BT 3 AND 7, LE 5, GT 5` )
      FOR GROUPS <group> OF wa IN itab
            GROUP BY COND string( WHEN wa BETWEEN 3 AND 7
                                              THEN `BT 3 AND 7`
                                 WHEN wa <= 5 THEN `LE 5`
                                              ELSE `GT 5` )
      LET members = VALUE i_tab(
                       FOR <member> IN GROUP <group> ( <member> ) )
      IN NEXT o = o->begin_section( <group>
                  )->write( members )->end_section( ) ).

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