When several quantity entries belong to the same warehouse, use COLLECT to build one total per warehouse without a separate lookup and update. It inserts a row for a new primary key and adds numeric fields when that key already exists.
Declare a hashed table with the warehouse as its unique key. Every field outside the primary key must be numeric; here, only units is summed. This self-contained report uses classic ABAP syntax and requires no database tables.
REPORT zcollect_warehouse_totals.
TYPES: BEGIN OF ty_total,
warehouse TYPE c LENGTH 4,
units TYPE i,
END OF ty_total.
DATA lt_totals TYPE HASHED TABLE OF ty_total
WITH UNIQUE KEY warehouse.
DATA ls_total TYPE ty_total.
START-OF-SELECTION.
ls_total-warehouse = 'W001'.
ls_total-units = 12.
COLLECT ls_total INTO lt_totals.
ls_total-warehouse = 'W002'.
ls_total-units = 5.
COLLECT ls_total INTO lt_totals.
ls_total-warehouse = 'W001'.
ls_total-units = 8.
COLLECT ls_total INTO lt_totals.
LOOP AT lt_totals INTO ls_total.
WRITE: / ls_total-warehouse, ls_total-units.
ENDLOOP.
Expected totals: W001 has 20 units and W002 has 5. The third COLLECT updates the existing W001 row, leaving two rows. Only combine quantities with compatible units; if units differ, include the unit in the primary key.
