ABAP Quick - Loop at Groups
Sometimes you want to loop through certain groups of a determined amount of data. With today's command we want to show you a simple method from the standard and a custom one.
If the determined data from the database should be structured in groups, there are different ways to do this. Once you could work with a second table that you summarized as far as the combinations you want to cover. Or take the path provided by SAP and work with groups that can be easily processed in a loop.
What you should pay attention to and how each variant works, we will briefly describe today and introduce to you a few examples.
With free processing according to your own methods, there are certainly many ways in which you can deal with the data and how you can form groups yourself. We want to introduce one of our methods to you here.
In the first step, we build a new table from the data, which we sort and group according to the elements we need. In our example, we take the company codes, which we sort by currency and country, then remove the duplicate entries on that basis.
" Create the group DATA(lt_group) = lt_t001. SORT lt_group BY waers land1. DELETE ADJACENT DUPLICATES FROM lt_group COMPARING waers land1.
Then you can start already with the processing. We process the data per group, but a certain amount of pre- and post-work can be done in the outer loop. In the inner loop you can work with the data.
LOOP AT lt_group ASSIGNING FIELD-SYMBOL(<ls_group>). " ... before processing LOOP AT lt_t001 ASSIGNING FIELD-SYMBOL(<ls_t001>) WHERE waers = <ls_group>-waers AND land1 = <ls_group>-land1. " processing ENDLOOP. " ... after processing ENDLOOP.
Work with groups
When processing with groups, pure SAP standard code comes into play. The way of working is very similar to our example, but you will save yourself the second table. But you also have to understand the logic.
LOOP AT lt_bukrs ASSIGNING FIELD-SYMBOL(<ls_bukrs>) GROUP BY ( waers = <ls_bukrs>-waers land1 = <ls_bukrs>-land1 ) ASSIGNING FIELD-SYMBOL(<ls_group>). " ... before processing LOOP AT GROUP <ls_group> ASSIGNING FIELD-SYMBOL(<ls_t001>). " processing ENDLOOP. " ... after processing ENDLOOP.
In the first loop, the group of elements is formed and assigned to a new field symbol for this group. This new field symbol contains only the fields of the group. The second loop is the loop over the group. With the addition AT GROUP, the group is addressed and the data is assigned to the new field symbol with all fields.
Processing via groups can be realized one way or the other. The standard way of grouping is a bit harder to read, but fully fulfills its purpose. The free way seems to be simpler in the first step, but you have to double the data and have to plan for a bit more processing power. Which way is the best for you, you should find out yourself.
SAP Documentation AT GROUP