处理结果如下所示:
*&---------------------------------------------------------------------*
*& Report ZTESTSQL
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*
REPORT ZTESTSQL.
TYPE-POOLS slis.
data: begin of w_test,
key type string, "这是关键字段,用于根据这列来统计的V1、V2的值(这个关键字段可以是多个)
v1 type i,
v2 type i,
end of w_test.
data: t_data like w_test occurs 0 with header line. "定义数据内表
data: t_test like HASHED TABLE OF w_test with UNIQUE key key with header line. "定义统计结果内表(必须是哈希内表)
*----------------------------------------------------------------------*
* assign value to internal tables
* 给内表赋值用于测试
*----------------------------------------------------------------------*
do 10 times.
if sy-index < 4.
t_data-key = 'A'.
t_data-v1 = sy-index.
t_data-v2 = sy-index + 1.
elseif sy-index < 7.
t_data-key = 'B'.
t_data-v1 = sy-index.
t_data-v2 = sy-index - 1.
else.
t_data-key = 'C'.
t_data-v1 = sy-index - 1.
t_data-v2 = sy-index - 2.
endif.
append t_data.
enddo.
*----------------------------------------------------------------------*
* process interal table
* 处理内表(统计)
*----------------------------------------------------------------------*
loop at t_data.
collect t_data into t_test. "按关键列统计值
endloop.
*----------------------------------------------------------------------*
* output internal tables
* 打印输出内表
*----------------------------------------------------------------------*
write: sy-uline.
write: '内表数据:'.
loop at t_data.
write: / ' ',t_data-key,t_data-v1, t_data-v2.
endloop.
write: sy-uline.
write: sy-uline.
write: 'collect后的数据:'.
loop at t_test.
write: / ' ',t_test-key, t_test-v1, t_test-v2.
endloop.
write: sy-uline.
由于collect统计只能有一个KEY,所以也可以用AT END OF做分组统计,必须先排序,参考zmmr603