"
Supported by

Get unique values of an internal table field

In SQL you can get a list of unique values of a field using DISTINCT. When the data is already in an internal table, before ABAP 7.40 you had to use a LOOP and a COLLECT.

But now that we live in more modern times, there is a simpler and more elegant way to achieve the same with a single command.

Like this:


TYPES ty_t_land1 TYPE STANDARD TABLE OF land1 WITH KEY table_line.

SELECT * FROM kna1 INTO TABLE @data(t_kna1).

DATA(t_land1) =  VALUE ty_t_land1(
    FOR GROUPS land1 OF wa IN t_kna1
    GROUP BY wa-land1 ASCENDING
    WITHOUT MEMBERS
    ( land1 ) ).

Nice? Nice!

Update: Vasco Nascimento noted that this code only works for flat structures and proposed an alternative which also works with deep structures:


TYPES:
  BEGIN OF ty_land1,
    land1 TYPE land1,
  END OF ty_land1.
TYPES ty_t_land1 TYPE STANDARD TABLE OF ty_land1.

SELECT * FROM kna1 INTO TABLE @data(t_kna1).

DATA(lt_land1) = VALUE ty_t_land1(
  FOR GROUPS land1 OF wa IN t_kna1
  GROUP BY wa-land1 ASCENDING
  WITHOUT MEMBERS
  ( land1 = land1 ) ).

Thank you Vasco!

Greetings from Abapinho.

Um comentário a “Get unique values of an internal table field”

  1. Vasco Nascimento Diz:

    Hi,
    The code above is for flat tables, another version of this code that works with structured tables:

    TYPES: begin of ty_land1,
    land1 type land1
    end of ty_land1.
    TYPES ty_t_land1 TYPE STANDARD TABLE OF ty_land1.

    DATA: lt_land1 type ty_t_land1.

    SELECT * FROM kna1 INTO TABLE @data(t_kna1).

    lt_land1 = VALUE #(
    FOR GROUPS land1 OF wa IN t_kna1
    GROUP BY wa-land1 ASCENDING
    WITHOUT MEMBERS
    ( land1 = land1 ) ).

Deixe um comentário


About Abapinho
Abapinho runs on WordPress
Articles (RSS) e Comments (RSS).