ABAP LOOP AT… GROUP BY Statement | A Tutorial for 2020
Following on from the previous topic in the advanced ABAP series, where we looked at the REDUCE operator, quite a few people mentioned and asked about the LOOP AT… GROUP BY statement and how that fits in with the REDUCE operator.
There is a brilliant blog post (one of many actually) by Horst Keller where he describes the possible uses and benefits of the LOOP AT… GROUP BY statement and where it might be used in your own projects. I followed his example and tried to break down exactly how this statement works and how you might use it properly.
DATA flights TYPE TABLE OF spfli WITH EMPTY KEY. SELECT * FROM spfli WHERE carrid = ‘…’ INTO TABLE @flights. DATA members LIKE flights. LOOP AT flights INTO DATA(flight) GROUP BY ( carrier = flight-carrid cityfr = flight-cityfrom ) ASCENDING ASSIGNING FIELD-SYMBOL(<group>). CLEAR members. LOOP AT GROUP <group> ASSIGNING FIELD-SYMBOL(<flight>). members = VALUE #( BASE members ( <flight> ) ). ENDLOOP. cl_demo_output=>write( members ). ENDLOOP. cl_demo_output=>display( ).
The basic idea is you get the data you need and then run through two LOOPs (they do not run as nested loops normally would). The first LOOP is where you use a key (which you can determine in a variety of ways) and isolate or build your groups. Then you use a second LOOP to run through the groups from the first LOOP and add your logic there by accessing the members of said group. In this case we simply displayed it in an output, but you could also do a host of other things with the grouped data,
The full solution can be found in the GitHub repo here.
If you have any questions, please feel free to comment down below and I’ll help where I can 🙂
Thanks for reading!