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

This example demonstrates simple control level processing using GROUP BY.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    DATA itab TYPE HASHED TABLE OF line
              WITH UNIQUE KEY col1 col2.

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

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

    out->write( itab )->line( ).

    DATA sum   TYPE line.
    DATA total TYPE line.
    DATA group LIKE itab.
    LOOP AT itab ASSIGNING FIELD-SYMBOL(<line>)
                 GROUP BY <line>-col1 ASCENDING.
      CLEAR sum.
      CLEAR group.
      LOOP AT GROUP <line> INTO DATA(line).
        group = VALUE #( BASE group ( line ) ).
        sum = sum( EXPORTING line = line
                             base = sum ).
      ENDLOOP.
      out->write( group )->line( )->write( sum )->line( ).
      total = sum( EXPORTING line = sum
                             base = total ).
    ENDLOOP.
    total-col1 = '*'.
    out->line( )->write( total )->display( ).

Description

This example works in the same way as the example for control level processing. Here, the group key is constructed explicitly using the value of the column col1 and, unlike in control level processing, does not depend on the structure of the table and its sorting.

The statement SUM is replaced by a functional method that replaces the implicit behavior of the statement with an explicit and self-defined function.

group and sum could also be filled by the evaluation of a table comprehension or table reduction using FOR ... IN GROUP, instead of in a member loop LOOP AT GROUP:

sum = REDUCE #( INIT s = VALUE line( )
                FOR line IN GROUP <line>
                NEXT s = sum( EXPORTING line = line
                                        base = s ) ).
group = #( FOR <wa> IN GROUP <line> ( <wa> ) ).

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