使用 FOR 循环添加字段的值

Adding the values of a field using FOR loop

如何使用 FOR 循环根据另一个字段中的相同值添加一个字段中的值?

Types:
Begin of ty_final,
  doctype type char5,
  posnr   type char5,
  total   type quan5,
End of ty_final.

DATA(lt_final) = VALUE ty_final( 
                     FOR line IN lt_history
                     WHERE ( hist_type = 'U' )
                     ( doctype = line-hist_type 
                       total   = line-quantity
                       posnr   = line-po_item  ) ). 

我在 LT_HISTORY 中有什么:

HIST_TYPE POSNR QUANTITY
   U       10    5
   U       10    2
   U       20    3
   U       20   -3

我在 LT_FINAL 中需要什么:

DOCTYPE POSNR QUANTITY
   U    10    7
   U    20    0

我正在尝试使用 GROUP BY 根据 POSNRDOCTYPE 字段获取 TOTAL 字段中值的总和。只是我不确定我需要在我的 FOR 循环中添加 GROUP BY 的确切位置。 REDUCE 让我头晕目眩。所以我尝试尽可能简单。

下面是最小的可重现示例,它使用 ABAP 单元(Ctrl+Shift+F10 到 运行)。我评论了您的代码并将其替换为解决方案:

CLASS ltc_test DEFINITION FOR TESTING
      DURATION SHORT RISK LEVEL HARMLESS.
  PRIVATE SECTION.
    METHODS test FOR TESTING.
ENDCLASS.
CLASS ltc_test IMPLEMENTATION.
  METHOD test.
    TYPES: BEGIN OF ty_line,
             doctype  TYPE c LENGTH 1,
             posnr    TYPE i,
             quantity TYPE i,
           END OF ty_line,
           ty_table TYPE STANDARD TABLE OF ty_line WITH DEFAULT KEY.
    DATA(lt_history) = VALUE ty_table(
        ( doctype = 'U' posnr = 10 quantity = 5 )
        ( doctype = 'U' posnr = 10 quantity = 2 )
        ( doctype = 'U' posnr = 20 quantity = 3 )
        ( doctype = 'U' posnr = 20 quantity = -3 ) ).
    DATA(lt_final) = VALUE ty_table(
*                         FOR line IN lt_history
*                         WHERE ( doctype = 'U' )
*                         ( doctype  = line-doctype
*                           quantity = line-quantity
*                           posnr    = line-posnr  ) ).
                         FOR GROUPS grp_line OF line IN lt_history
                         WHERE ( doctype = 'U' )
                         GROUP BY ( doctype = line-doctype posnr = line-posnr )
                         ( doctype  = grp_line-doctype
                           quantity = REDUCE #( INIT t = 0 FOR <line> IN GROUP grp_line 
                                                NEXT t = t + <line>-quantity )
                           posnr    = grp_line-posnr  ) ).
    cl_abap_unit_assert=>assert_equals( act = lt_final exp = VALUE ty_table(
        ( doctype = 'U' posnr = 10 quantity = 7 )
        ( doctype = 'U' posnr = 20 quantity = 0 ) ) ).
  ENDMETHOD.
ENDCLASS.