There are many occasion in which COLLECT comes as the first option when you want to sum up some fields. Just writing COLLECT wa IN itab will do the trick. But, there is always a "but". What I don't like about it is how quick you can screw up the logic. You either have to be extra careful to define the keys of the internal table or to be sure that the structure will not sum up fields you don't want to (in a standard table without keys it sums up all numeric data type field). This made me ask myself: is there a way to write this better? And to make it even better, use the new ABAP syntax ?

Let's see the following example I wrote below:

TYPES:
  BEGIN OF ts_sales_order_item,
    material      TYPE matnr,
    item_price    TYPE netwr_ap,
    item_quantity TYPE kwmeng,
  END OF ts_sales_order_item,
  tt_sales_order_item TYPE STANDARD TABLE OF ts_sales_order_item WITH DEFAULT KEY.

SELECT matnr  AS material,
       ntgew  AS item_price,
       kwmeng AS item_quantity
  FROM vbap
    UP TO 10 ROWS
    INTO TABLE @DATA(lt_data).

DATA(lt_sales_order_item) = VALUE tt_sales_order_item(
        FOR GROUPS <group_key> OF <group> IN lt_data GROUP BY ( material = <group>-material )
          LET coll_line = REDUCE #(
              INIT line TYPE ts_sales_order_item FOR <member> IN GROUP <group_key>
              NEXT line-material      = <member>-material
                   line-item_price    = ( line-item_price + <member>-item_price ) / 2
                   line-item_quantity = line-item_quantity + <member>-item_quantity )
          IN ( coll_line ) ) .

cl_demo_output=>write( lt_sales_order_item ).

cl_demo_output=>display( ).

I know, this can look discouraging. Where is the LOOP? My idea was to write everything in one processing block using the new syntax.
If you follow the logic closely, this block has 3 ( or 4 ) main points:

  1. FOR GROUP -> this is the same as LOOP AT GROUP
  2. LET coll_line = REDUCE -> the hole group will be reduced into one line
  3. FOR <m> IN GROUP <group_key> NEXT -> here we make the necessary calculation
  4. IN ( coll_line ) -> last line. We append the result line to the new table.

Now that I look at it, I am not sure if I really want to replace anymore COLLECT. Just kidding. This piece of code is easy to be enhanced both with new values or new keys. You have complete control over it. As it can be seen, I can applay any logic needed.
Though, if you are concerned about readability or complexity then a similar option is using LOOP AT GROUP. You will achieve the same result, and it will be easier to read.

The whole idea of this article is: if you don't like COLLECT, there are more options on the market where to choose from.