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 Table, Grouping with FOR for Aggregates

This example demonstrates aggregates with FOR expressions.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    TYPES:
      BEGIN OF aggregate,
        sum TYPE i,
        max TYPE i,
        min TYPE i,
        avg TYPE decfloat34,
      END OF aggregate.
    DATA out TYPE REF TO if_demo_output.

    initialize( ).

    out = REDUCE #(
      INIT o = cl_demo_output=>new(
                 )->next_section( `Table` )->WRITE( numbers )
           aggregate = VALUE aggregate( )
           MEMBERS   = VALUE itab( )
      FOR GROUPS <group_key> OF <wa> IN numbers
            GROUP BY ( key = <wa>-key count = GROUP SIZE )
            ASCENDING
      NEXT aggregate = VALUE #(
             sum = REDUCE i( INIT SUM = 0
                     FOR m IN GROUP <group_key>
                     NEXT sum = sum + m-num )
             max = REDUCE i( INIT max = 0
                     FOR m IN GROUP <group_key>
                     NEXT max = nmax( val1 = max
                                     val2 = m-num ) )
             min = REDUCE i( INIT MIN = 101
                     FOR m IN GROUP <group_key>
                     NEXT min = nmin( val1 = min
                                val2 = m-num ) )
             avg = aggregate-sum / <group_key>-count )
           members = sort(
                       VALUE itab( FOR m IN GROUP <group_key> ( m ) ) )
           o = o->next_section( |Group Key: { <group_key>-key }|
             )->WRITE( MEMBERS
             )->WRITE( aggregate ) ).

    out->display( ).

Description

This example works in the same way as the example for group loops with member loops and the example for group loops without member loops. Here, the group loop is also replaced by a FOR expression. The aggregates are calculated in a VALUE expression, to avoid having to specify the name of the structure too often. The descending sort of the member table members must be passed to a method here, since there is no corresponding additions in table comprehensions.