第一个案例:原文链接:https://blog.csdn.net/lmf496891416/article/details/111317377
第一步:定义结构,此处定义了三个字段 key1 ,key2 ,col ,然后定义表 itab 参照结构 struct
TYPES: BEGIN OF ty_employee,name TYPE char30,role TYPE char30,age TYPE i,sex TYPE char10,END OF ty_employee,
ty_employee_t TYPE STANDARD TABLE OF ty_employee WITH KEY name.
第二步,赋值
DATA(gt_employee) = VALUE ty_employee_t(
( name = 'John' role = 'ABAP guru' age = 34 sex = 'MAN' )
( name = 'Alice' role = 'FI Consultant' age = 42 sex = 'WOMAN' )
( name = 'Barry' role = 'ABAP guru' age = 54 sex = 'WOMAN' )
( name = 'Mary' role = 'FI Consultant' age = 37 sex = 'WOMAN' )
( name = 'Arthur' role = 'ABAP guru' age = 34 sex = 'MAN' )
( name = 'Mandy' role = 'SD Consultant' age = 64 sex = 'MAN' ) ).
第三步:loop group by
第一个循环先从第一行 ABAP guru开始 ,然后可以看到有3个 ABAP guru,所以 SIZE = 3 ,这是第一组,所以 index = 1
然后第二个循环,将组中的数据读出来计算平均年龄,这时候把3个ABAP guru拿出来,计算平均年龄
然后回到第一个循环,从第二行FI Consultant 开始,然后可以看到有2个FI Consultant。所以SIZE = 2 ,这是第二组 ,所以 index = 2
然后在第二个循环中,将组中的数据读取出来,然后输出
下面同理
LOOP AT gt_employee INTO DATA(ls_employee) GROUP BY ( role = ls_employee-rolesize = GROUP SIZE "分组组数"index = GROUP INDEX ) "分组的组序号"ASCENDING ASSIGNING FIELD-SYMBOL(<group>).CLEAR: gv_tot_age.WRITE: / | 组序号: { <group>-index } 角色: { <group>-role WIDTH = 15 }|& | 这个组有几条数据: { <group>-size } |."loop循环组,将组里的数据读出来"LOOP AT GROUP <group> ASSIGNING FIELD-SYMBOL(<ls_member>).gv_tot_age = gv_tot_age + <ls_member>-age.WRITE: /13 <ls_member>-name .ENDLOOP.gv_avg_age = gv_tot_age / <group>-size.WRITE: / |组平均年龄: { gv_avg_age }|.SKIP.
ENDLOOP.
得到效果如下
第二个案例:(待完善)