需求场景:
在abap中内表汇总数据是很常见的一个场景,我平时用的最多的就是COLLECT,但是也有不方便的地方,每次都要DATA一个新的内表,并且只能保留跟汇总相关的字段,不是很方便,今天总结一下常见的几种方式。
准备测试数据
DATA: BEGIN OF lw_data,
matnr TYPE matnr,
werks TYPE werks_d,
menge TYPE menge_d,
END OF lw_data.
DATA: lt_data LIKE TABLE OF lw_data.
DATA: BEGIN OF lw_sum,
matnr TYPE matnr,
werks TYPE werks_d,
menge TYPE menge_d,
END OF lw_sum.
DATA: lt_sum LIKE TABLE OF lw_sum.
START-OF-SELECTION.
*准备数据
lt_data = VALUE #(
( matnr = 'M1' werks = 'W1' menge = 10 )
( matnr = 'M1' werks = 'W1' menge = 10 )
( matnr = 'M2' werks = 'W1' menge = 20 )
( matnr = 'M1' werks = 'W2' menge = 30 )
( matnr = 'M2' werks = 'W2' menge = 40 )
).
1. 通过COLLECT 语句汇总
局限性:不参与统计的字段必须清空.
REFRESH lt_sum.
LOOP AT lt_data INTO lw_data.
CLEAR lw_sum.
lw_sum-matnr = lw_data-matnr.
lw_sum-werks = lw_data-werks.
lw_sum-menge = lw_data-menge.
COLLECT lw_sum INTO lt_sum.
ENDLOOP.
cl_demo_output=>display( lt_sum ).
输出结果
2. 通过AT NEW 语句实现
局限性:参与统计的字段必须是内表前面的字段,并且需要实现排序
REFRESH lt_sum.
SORT lt_data BY matnr werks.
LOOP AT lt_data INTO lw_data.
AT NEW werks.
CLEAR lw_sum.
lw_sum-matnr = lw_data-matnr.
lw_sum-werks = lw_data-werks.
ENDAT.
lw_sum-menge = lw_sum-menge + lw_data-menge.
AT END OF werks.
APPEND lw_sum TO lt_sum.
ENDAT.
ENDLOOP.
输出结果
3. 通过LOOP AT GROUP 实现
局限性:该语句无需排序,字段无需作为内表前面的字段, 但是性能比AT NEW 方式差.
这个S4版本才支持,目前我用的是ECC版本,无法测试,如果用上了S4后才补充进来。
4. 通过READ 哈希表实现
这个比较通用
DATA: lt_sum_hs LIKE HASHED TABLE OF lw_sum WITH UNIQUE KEY matnr werks.
REFRESH lt_sum_hs.
LOOP AT lt_data INTO lw_data.
READ TABLE lt_sum_hs ASSIGNING FIELD-SYMBOL(<fs_sum>) WITH TABLE KEY matnr = lw_data-matnr werks = lw_data-werks.
IF sy-subrc <> 0.
CLEAR lw_sum.
lw_sum-matnr = lw_data-matnr.
lw_sum-werks = lw_data-werks.
INSERT lw_sum INTO TABLE lt_sum_hs ASSIGNING <fs_sum>.
ENDIF.
IF <fs_sum> IS ASSIGNED.
<fs_sum>-menge = <fs_sum>-menge + lw_data-menge.
ENDIF.
ENDLOOP.
cl_demo_output=>display( lt_sum ).