Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Aggregating rows in SAP ABAP with the same name
You can use the COLLECT keyword or some aggregate functions to achieve the result of aggregating rows with the same name in SAP ABAP. You should define appropriate data types to match your specific scenario.
The COLLECT statement is particularly useful for accumulating numeric values while grouping rows by key fields. It automatically sums up non-key fields for records that have identical key field values.
Example
Here's a complete example showing how to aggregate rows using the COLLECT statement ?
TYPES: BEGIN OF t_my_type,
key_a TYPE i,
key_b TYPE i,
nokey_c TYPE i,
nokey_d TYPE i,
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 UNIQUE KEY key_a key_b.
DATA: lt_result TYPE tt_my_type_list,
lt_sums TYPE tt_my_type_hash,
ls_data TYPE t_my_type.
FIELD-SYMBOLS: <ls_result> TYPE t_my_type.
* Sample data preparation
ls_data-key_a = 1.
ls_data-key_b = 10.
ls_data-nokey_c = 100.
ls_data-nokey_d = 200.
APPEND ls_data TO lt_result.
ls_data-key_a = 1.
ls_data-key_b = 10.
ls_data-nokey_c = 50.
ls_data-nokey_d = 75.
APPEND ls_data TO lt_result.
ls_data-key_a = 2.
ls_data-key_b = 20.
ls_data-nokey_c = 300.
ls_data-nokey_d = 400.
APPEND ls_data TO lt_result.
* Aggregate rows using COLLECT
LOOP AT lt_result ASSIGNING <ls_result>.
COLLECT <ls_result> INTO lt_sums.
ENDLOOP.
In this example, the COLLECT statement will group records by the key fields (key_a and key_b) and automatically sum the numeric values in the non-key fields (nokey_c and nokey_d). Records with identical key values will be combined into a single entry with aggregated totals.
The hashed table lt_sums uses the key fields for efficient lookup and ensures that duplicate keys are handled properly during the aggregation process.
Conclusion
The COLLECT statement provides an efficient way to aggregate numeric data in SAP ABAP by automatically grouping rows with identical key fields and summing their non-key numeric values.
