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 Table, Grouping with LOOP and FOR

This example demonstrates aggregates using table reductions.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    initialize( ).

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

    DATA:
      BEGIN OF aggregate,
        sum TYPE i,
        max TYPE i,
        min TYPE i,
        avg TYPE decfloat34,
      END OF aggregate.

    out->next_section( `Table`
      )->write( numbers ).

    LOOP AT numbers ASSIGNING FIELD-SYMBOL(<wa>)
         GROUP BY ( key = <wa>-key  count = GROUP SIZE )
         ASCENDING
         ASSIGNING FIELD-SYMBOL(<group_key>).

      out->next_section( |Group Key: { <group_key>-key }| ).
      DATA(members) = VALUE itab( FOR m IN GROUP <group_key> ( m ) ).
      aggregate-sum = REDUCE i( INIT sum = 0
                               FOR m IN GROUP <group_key>
                               NEXT sum = sum + m-num ).
      aggregate-max = REDUCE i( INIT max = 0
                               FOR m IN GROUP <group_key>
                               NEXT max = nmax( val1 = max
                                                val2 = m-num ) ).
      aggregate-min = REDUCE i( INIT min = 101
                               FOR m IN GROUP <group_key>
                               NEXT min = nmin( val1 = min
                                                val2 = m-num ) ).
      aggregate-avg = aggregate-sum / <group_key>-count.

      SORT members BY num DESCENDING.
      out->write( members
        )->write( aggregate ).
    ENDLOOP.
    out->display( ).

Description

This example works in the same way as the example for aggregates. Here, expressions FOR ... IN GROUP are used instead of the member loop to calculate aggregates using table reductions and to determine the group members using a table comprehension. A further example demonstrates how the entire group loop can be implemented using expressions.