最近發現SAP提供了好多功能,就拿collect來說,之前也用到這樣的功能,但是都是自己手工寫的代碼,現在有了它,以後處理內表中的數據按某些列來統計數據就方便多了!collect可以用於select.....endselect,也可以用於內表中的數據處理,但是不推薦在select....endselect中使用。collect是根據某些關鍵列來分類統計數據某些數字列的和的過程,下列通過一個例子來了解collect的用法:
處理結果如下所示:
程序如下所示:
*&---------------------------------------------------------------------*
*& Report ZTEST_COLLECT
*&
*&---------------------------------------------------------------------*
*& Create By : flying
*& Create Date : 2009-12-31
*& Descriptions : 測試collect的用法
*&---------------------------------------------------------------------*
REPORT ZTEST_COLLECT.
*----------------------------------------------------------------------*
* define internal tables or workarea
* 定義內表或者工作區
*----------------------------------------------------------------------*
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.
abap collect的用法與實例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.