Aggregating rows

alexander.skibin picture alexander.skibin · May 14, 2014 · Viewed 21.9k times · Source

In sap I have a table, there are rows with the same name but with different quantity. I want to summarize this rows like this:

    SELECT c~aufnr
           p~matnr p~bdter p~meins p~baugr p~dbskz p~erfmg p~aufnr
           f~maktx
       INTO CORRESPONDING FIELDS OF TABLE it_tab
       FROM  afpo AS c
         INNER JOIN resb AS p ON c~aufnr = p~aufnr
         INNER JOIN makt AS f ON p~matnr = f~matnr.             

    LOOP AT it_tab INTO fs_tab.
       COLLECT fs_tab INTO it_tab_collected.
    ENDLOOP.
    it_tab = it_tab_collected.

But in this case it sums only absolutelly identically rows. I need to sum up rows only with the same name.

How can I achieve this?

Regards, Alexander.

Answer

vwegert picture vwegert · May 14, 2014

As icbytes already said, COLLECT uses the key fields to determine which fields to aggregate. I would suggest defining some data types to match your scenarion:

TYPES: BEGIN OF t_my_type,
         key_a TYPE foo,
         key_b TYPE foo,
         nokey_c TYPE foo,
         nokey_d TYPE foo,
       END OF t_my_type,
       tt_my_type_list TYPE STANDARD TABLE OF t_my_type WITH DEFAULT KEY,
       tt_my_type_hash TYPE HASHED TABLE OF t_my_type WITH KEY key_a key_b.

DATA: lt_result TYPE tt_my_type_list,
      lt_sums   TYPE tt_my_type_hash.

FIELD-SYMBOLS: <ls_result> TYPE t_my_type.

LOOP AT lt_result ASSIGNING <ls_result>.
  COLLECT <ls_result> INTO lt_sums.
ENDLOOP.

...or you might want to use an aggregate function in the first place...