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 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) = cl_demo_output=>new( ).
DATA members LIKE itab.
out->begin_section( `LE 5, BT 2 AND 7, GT 5` ).
LOOP AT itab INTO DATA(wa)
GROUP BY COND string( WHEN wa <= 5 THEN `LE 5`
WHEN wa > 2 AND
wa <= 7 THEN `BT 2 AND 7`
WHEN wa > 5 THEN `GT 5` )
ASSIGNING FIELD-SYMBOL(<group>).
out->begin_section( <group> ).
CLEAR members.
LOOP AT GROUP <group> ASSIGNING FIELD-SYMBOL(<wa>).
members = VALUE #( BASE members ( <wa> ) ).
ENDLOOP.
out->write( members )->end_section( ).
ENDLOOP.
out->next_section( `BT 2 AND 7, LE 5, GT 5` ).
LOOP AT itab INTO wa
GROUP BY COND string( WHEN wa > 2 AND
wa <= 7 THEN `BT 2 AND 7`
WHEN wa <= 5 THEN `LE 5`
WHEN wa > 5 THEN `GT 5` )
ASSIGNING <group>.
out->begin_section( <group> ).
CLEAR members.
LOOP AT GROUP <group> ASSIGNING <wa>.
members = VALUE #( BASE members ( <wa> ) ).
ENDLOOP.
out->write( members )->end_section( ).
ENDLOOP.
out->display( ).
Description
This example works in a similar way to the example for constructions using comparison expressions. The following shows how the result depends on the order in which expressions are evaluated if the comparison expressions overlap.
In the first group loop,
- those rows are identified first whose value is less than or equal to 5,
- then the rows whose value is between 2 and 7,
- then the rows whose value is greater than 5.
In the second group loop,
- those rows are identified first whose value is between 2 and 7,
- then the rows whose value is less than or equal to 5,
- then the rows whose value is greater than 5.
The result of this is that the rows with the values 3, 4, and 5 are assigned to different groups. The groups of the rows would not change, however, even if the internal table were sorted differently.
The example for grouping with FOR
demonstrates how the entire group loop can be implemented using expressions.