duplicatesabapinternal-tables

ABAP flag duplicate values in internal table


I need to flag the duplicate values and I found a solution using the code below:

sort result_package stable by knumh zzklfn1.
data lv_prev_knumh type c length 10.

loop at result_package assigning <result_fields>.
  if <result_fields>-knumh <> lv_prev_knumh.
    lv_prev_knumh = <result_fields>-knumh.
    <result_fields>-zzstafkz = ''.
  else.
    <result_fields>-zzstafkz = 'X'.
  endif.
endloop.

But obviously the first duplicated value is not flagged. Output is shown below:

knumh zzstafkz
001
002
002 x
002 x
003

I don't know really what should I do next.


Solution

  • You can simply do it by keeping the reference to the previous record and assign X flag when the condition meets.

    Types declaration and sample data for test:

    TYPES: BEGIN OF ty_result_package,
             knumh    TYPE knumh,
             zzstafkz TYPE flag,
           END OF ty_result_package,
           ty_t_result_package TYPE STANDARD TABLE OF ty_result_package
                               WITH DEFAULT KEY.
    
    DATA(lt_result_package) = VALUE ty_t_result_package(
        ( knumh = '001'  )
        ( knumh = '002'  ) ( knumh = '002'  ) ( knumh = '002'  )
        ( knumh = '003'  )
        ( knumh = '004'  ) ( knumh = '004'  ) ).
    

    The logic itself:

    FIELD-SYMBOLS: <fs_result_package_prev> type ty_result_package.
    
    SORT lt_result_package BY knumh ASCENDING.
    LOOP AT lt_result_package ASSIGNING FIELD-SYMBOL(<fs_result_package>).
      IF <fs_result_package_prev> IS ASSIGNED AND
         <fs_result_package>-knumh = <fs_result_package_prev>-knumh.
    
        <fs_result_package_prev>-zzstafkz = <fs_result_package>-zzstafkz = 'X'.
      ELSE.
        CLEAR <fs_result_package>-zzstafkz.  " clear the flag if necessary
      ENDIF.
    
      ASSIGN <fs_result_package> TO <fs_result_package_prev>.
    ENDLOOP.
    

    Sample output:

    cl_demo_output=>display_data( EXPORTING value = lt_result_package ).
    

    lt_result_package