typesduplicatesabapinternal-tables

Select dup indices into a nested internal table in each table row?


I have the following code to find the duplicates in an itab:

TYPES: BEGIN OF ty_duplicates,
  id type i,
  END OF ty_duplicates.
TYPES _duplicates type STANDARD TABLE OF ty_duplicates WITH NON-UNIQUE DEFAULT KEY.

DATA(table_with_duplicates) = VALUE _duplicates( ( id = 1 ) ( id = 2 ) ( id = 1 ) ( id = 3 ) ( id = 3 ) ).

DATA(duplicates) = VALUE string_table( FOR GROUPS <group> OF <line> IN table_with_duplicates
GROUP BY ( id = <line>-id size = GROUP SIZE )
    ( LINES OF COND #( WHEN <group>-size > 1 THEN VALUE string_table( (
concat_lines_of(
    table = VALUE string_table(
            FOR <line2> IN GROUP <group> INDEX INTO idx ( |{ idx }| ) )
    sep   = ',' ) ) ) ) ) ).

  cl_demo_output=>display_data(
    EXPORTING
      value = duplicates
  ).

Sadly with this code, the indices of the duplicates get written into one line as a string.

How would I go on to change this code so I get instead a nested table inside each line, where each index is a separate line in it? So the result would look similar to this:

DATA(indices) = VALUE #( 
( ( index1 ) ( index2 ) ) (  ( index1 ) ( index2 ) )  "and so on..
).

Solution

  • In this case we need to have a kind of a nested table type, i.e. table inside a table, so start with defining an appropriate type for it. I named it ty_t_string_table, so it is a table, where each element is a table of type string_table:

    TYPES: ty_t_string_table TYPE STANDARD TABLE OF string_table 
                             WITH NON-UNIQUE DEFAULT KEY.
    

    Afterwards we do not need to make a concatenation of the ids inside a table element, but to create the table itself. The code for it:

      DATA(duplicates) = VALUE ty_t_string_table(
        FOR GROUPS <group> OF <line> IN table_with_duplicates
        GROUP BY ( id = <line>-id size = GROUP SIZE )
        ( LINES OF COND #( WHEN <group>-size > 1 THEN VALUE #(
    
          ( VALUE #( FOR <line2> IN GROUP <group> INDEX INTO idx ( |{ idx }| ) ) )
    
        ) ) )
      ).
    

    It is enough to specify the type ty_t_string_table VALUE ty_t_string_table( only by the fist value declaration, inside we do not need to mention types again and just use #(, the types of a table and its component would be automatically derived.

    Note that displaying nested tables is not supported by cl_demo_output=>display_data, so set a breakpoint to check the result.

    ty_t_string_table string_table string_table