In this SAP ABAP tutorial I will show you the use COLLECT STATEMENT in SAP ABAP
Collect statement is used to summarize the data of the internal
table.
SYNTAX : collect <work_area> into
<internal_table>.
Some points before using collect statement:
1. Before
using collect statement , all the fields of an internal table that are not part of the key of the table
should be of numeric type ( f, p, i).
2. When
we use collect statement to add a
new line or record in an internal table, the SAP system checks whether the line
with the same key value already exist in the table. IF no such line exists,
then collect will act as a normal append.
However, if the line having the same key value is found in the internal table, the collect statement will adds the content of the numeric field in the work area with the contents of the numeric fields in the existing entry of the table.
However, if the line having the same key value is found in the internal table, the collect statement will adds the content of the numeric field in the work area with the contents of the numeric fields in the existing entry of the table.
Program :
REPORT ztest_r_05.
TYPES : BEGIN OF ty_shop,
item TYPE char10,
quantity TYPE i,
amount TYPE i,
END OF ty_shop.
DATA : lt_shop TYPE STANDARD TABLE OF ty_shop INITIAL SIZE 1,
ls_shop TYPE ty_shop,
lt_shop_summ LIKE lt_shop.
FIELD-SYMBOLS : <fs_shop> TYPE ty_shop.
DO 6 TIMES.
CASE sy-index.
WHEN 1.
ls_shop-item = 'SOAP'.
ls_shop-quantity = 1.
ls_shop-amount = 50.
APPEND ls_shop TO lt_shop.
CLEAR ls_shop.
WHEN 2.
ls_shop-item = 'SAMPOO'.
ls_shop-quantity = 1.
ls_shop-amount = 120.
APPEND ls_shop TO lt_shop.
CLEAR ls_shop.
WHEN 3.
ls_shop-item = 'FACE_WASH'.
ls_shop-quantity = 1.
ls_shop-amount = 100.
APPEND ls_shop TO lt_shop.
CLEAR ls_shop.
WHEN 4.
ls_shop-item = 'SOAP'.
ls_shop-quantity = 1.
ls_shop-amount = 70.
APPEND ls_shop TO lt_shop.
CLEAR ls_shop.
WHEN 5.
ls_shop-item = 'SAMPOO'.
ls_shop-quantity = 1.
ls_shop-amount = 200.
APPEND ls_shop TO lt_shop.
CLEAR ls_shop.
WHEN 6.
ls_shop-item = 'FACE_WASH'.
ls_shop-quantity = 1.
ls_shop-amount = 240.
APPEND ls_shop TO lt_shop.
CLEAR ls_shop.
WHEN OTHERS.
ENDCASE.
ENDDO.
LOOP AT lt_shop ASSIGNING <fs_shop>.
WRITE : / <fs_shop>-item , <fs_shop>-quantity, <fs_shop>-amount.
ENDLOOP.
ULINE.
WRITE : / 'Summarized records using Collect statement'.
LOOP AT lt_shop INTO ls_shop.
COLLECT ls_shop INTO lt_shop_summ.
ENDLOOP.
LOOP AT lt_shop_summ INTO ls_shop.
WRITE : / <fs_shop>-item , <fs_shop>-quantity, <fs_shop>-amount.
ENDLOOP.