从内部表的一列或多列中提取唯一值的最有效方法是什么?
What is the most efficient way to extract the unique values from a column or multiple columns of an internal table?
推荐答案如果你有 7.40 SP08 或更高版本,你可以简单地使用内联语法来填充目标表(不需要 LOOP GROUP BY):
If you have 7.40 SP08 or above you can simply use the inline syntax to populate the target table (no need for LOOP GROUP BY):
DATA: it_unique TYPE STANDARD TABLE OF fieldtype. it_unique = VALUE #( FOR GROUPS value OF <line> IN it_itab GROUP BY <line>-field WITHOUT MEMBERS ( value ) ).这适用于任何类型的目标表.
This works with any type of the target table.
对于旧版本,请使用:
DATA: it_unique TYPE HASHED TABLE OF fieldtype WITH UNIQUE KEY table_line. LOOP AT it_itab ASSIGNING <line>. INSERT <line>-field INTO TABLE lt_unique. ENDLOOP.以上也适用于排序表.尽管我不建议为此使用排序表,除非您确实确定结果中只有几行.
The above works with sorted tables as well. Although I do not recommend to use sorted tables for this purpose unless you are really sure that only a few lines will be in the result.
INSERT 的非零 sy-subrc 被简单地忽略.无需进行两次密钥查找(一次用于存在检查,一次用于插入).
The non-zero sy-subrc of INSERT is simply ignored. No need to do the key lookup twice (once for existence check, once for insert).
如果目标必须是一个标准表并且您有一个旧的 ABAP 堆栈,您可以选择使用
If the target must be a STANDARD TABLE and you have an old ABAP stack you can alternatively use
DATA: it_unique TYPE STANDARD TABLE OF fieldtype. LOOP AT it_itab ASSIGNING <line>. READ TABLE lt_unique WITH TABLE KEY table_line = <line>-field TRANSPORTING NO FIELDS BINARY SEARCH. INSERT <line>-field INTO lt_unique INDEX sy-tabix. ENDLOOP.这提供了与排序表相同的行为,但使用的是标准表.这是否比 SORT/DELETE ADJACENT DUPLICATES 更有效取决于 itab 中重复条目的数量.存在的重复条目越多,上述解决方案就越快,因为它避免了对目标表进行不必要的追加.但另一方面,追加比插入快.
This provides the same behavior as with a sorted table but with a standard table. Whether this is more efficient than SORT / DELETE ADJACENT DUPLICATES depends on the number of duplicate entries in itab. The more duplicate entries exist the faster will be the above solution because it avoids the unnecessary appends to the target table. But on the other side appends are faster than inserts.
更多推荐
从内部表中提取唯一值
发布评论