ABAP程序内表中的数量和金额字段 经常会需要合计, SUM和COLLECT 语法都能实现对数量和金额字段的合计。
1. SUM语法
ABAP中SUM语句比不上EXCEL里的强大;
SUM只能在loop循环中使用,一般和AT-ENDAT配合使用。
使用SUM语句的先决条件包含在loop中使用加法INTO,以及指定的工作区域wa与内部表的行类型兼容。此外,当内部表itab的行类型包含表组件时,不能使用SUM。
DEMO
DATA: BEGIN OF wa, col1 TYPE i, col2 TYPE i, END OF wa, itab LIKE TABLE OF wa WITH EMPTY KEY. itab = VALUE #( FOR i = 1 UNTIL i > 5 FOR j = 1 UNTIL j > i ( col1 = i col2 = j ) ). LOOP AT itab INTO wa. AT END OF col1. SUM. cl_demo_output=>write( wa ). ENDAT. ENDLOOP. cl_demo_output=>display( wa ).
内表ITAB中有15行数据
显示:
2. COLLECT语法
语法:COLLECT wa INTO itab [result].
此语句将工作区域的内容作为内部表itab中的单行插入,或者将其数值组件的值添加到具有相同主表键的现有行的对应值中。会对 数值型字段:I 类型, QUAN 类型,CURR类型的字段做汇总,字符型字段视为汇总条件。
*&---------------------------------------------------------------------* *& Report YCX_COLLECT1 *&---------------------------------------------------------------------* *& *&---------------------------------------------------------------------* REPORT ycx_collect1. TYPES: BEGIN OF line, key TYPE c LENGTH 1, num TYPE i, END OF line. DATA itab TYPE SORTED TABLE OF line WITH UNIQUE KEY key. DATA(rnd) = cl_abap_random_int=>create( seed = + sy-uzeit min = 1 max = 3 ). DO. COLLECT VALUE line( key = COND #( LET r = rnd->get_next( ) IN WHEN r = 1 THEN 'X' WHEN r = 2 THEN 'Y' WHEN r = 3 THEN 'Z' ) num = 1 ) INTO itab ASSIGNING FIELD-SYMBOL(<fs>). IF <fs>-num = 100. EXIT. ENDIF. ENDDO. cl_demo_output=>display( itab ).
示例展示 sum和collect 实现汇总
*&---------------------------------------------------------------------* *& Report YCX_SUM *&---------------------------------------------------------------------* *& *&---------------------------------------------------------------------* REPORT ycx_sum. DATA: BEGIN OF line, col1 TYPE c, col2 TYPE i, END OF line. DATA: itab LIKE line OCCURS 10, lt_collect LIKE line OCCURS 0 WITH HEADER LINE. DO 3 TIMES. line-col1 = sy-index. line-col2 = sy-index ** 3. APPEND line TO itab. ENDDO. **显示内表数据 LOOP AT itab INTO line. WRITE: / line-col1, line-col2. ENDLOOP. WRITE:/'SUM汇总数据'. **使用SUM 汇总 LOOP AT itab INTO line. AT END OF col1. SUM. WRITE: / line-col1, line-col2. ENDAT. ENDLOOP. WRITE:/'SUM汇(不使用AT END OF)'. **使用SUM 汇总 LOOP AT itab INTO line. SUM. WRITE: / line-col1, line-col2. ENDLOOP. **使用COLLECT 汇总 LOOP AT itab INTO line. lt_collect-col1 = line-col1. lt_collect-col2 = line-col2. COLLECT lt_collect. CLEAR: lt_collect. ENDLOOP. WRITE:/'COLLECT汇总数据'. LOOP AT lt_collect. WRITE: / lt_collect-col1, lt_collect-col2. ENDLOOP.