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 Control Levels

This example demonstrates simple control level processing using GROUP BY in a FOR expression.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    DATA itab TYPE i_tab.

    itab = VALUE #(
      FOR j = 1 UNTIL j > 3
       ( col1 = 'A'
         col2 = j
         col3 = j ** 2 )
       ( col1 = 'B'
         col2 = 2 * j
         col3 = ( 2 * j ) ** 2 ) ).

    DATA(out) = cl_demo_output=>new( )->write( itab )->line( ).

    DATA(total) = REDUCE line(
      INIT t = VALUE line( )
      FOR GROUPS OF <line> IN itab GROUP BY <line>-col1 ASCENDING
      LET sum = REDUCE line( INIT s = VALUE line( )
                             FOR line IN GROUP <line>
                             NEXT s = sum( EXPORTING line = line
                                                   base = s ) )
          group = VALUE i_tab( FOR <wa> IN GROUP <line> ( <wa> ) )
          o = out->write( group )->line( )->write( sum )->line( ) IN
      NEXT t = sum( EXPORTING
                          line = VALUE line( BASE sum col1 = '*' )
                          base = t ) ).

    out->line( )->display( total ).

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 structure to which the total of the numeric columns is written. The subtotals and the group members are written to the local auxiliary variables sum and members using a further table reduction and a table comprehension. This table reduction table comprehension could also be used in the example for LOOP AT ... GROUP BY instead of the member loop.