u/Substantial_Half6347

▲ 5 r/abap

ABAP: Best way to count item rows per header row — DB aggregation vs internal table processing?

Hi everyone,

I’m working on an ABAP report where I have a header internal table and an item internal table.

The header table is something like:

gt_header
- seq_no
- vbeln_so
- item_cnt

The item table is something like:

gt_item
- seq_no
- vbeln_so
- posnr
- ...

What I want to do is set the number of item rows for each header row.

My first approach was something like this:

LOOP AT gt_header ASSIGNING FIELD-SYMBOL(<fs_header>).

DATA(lt_item_temp) = gt_item.

DELETE lt_item_temp WHERE seq_no <> <fs_header>-seq_no.

DESCRIBE TABLE lt_item_temp LINES <fs_header>-item_cnt.

ENDLOOP.

But I realized this is probably inefficient because it copies the whole item table for every header row and then deletes most rows.

Another approach I considered was:

SORT gt_item BY seq_no.

LOOP AT gt_header ASSIGNING FIELD-SYMBOL(<fs_header>).

DATA(lv_cnt) = 0.

LOOP AT gt_item TRANSPORTING NO FIELDS
WHERE seq_no = <fs_header>-seq_no.

lv_cnt = lv_cnt + 1.

ENDLOOP.

<fs_header>-item_cnt = lv_cnt.

ENDLOOP.

However, I’m not sure whether SORT + LOOP WHERE on a standard internal table really uses the sorted order efficiently, or whether it still scans more rows than expected.

I’m thinking of these options:

  1. Count the item rows directly in SQL using COUNT(*) and GROUP BY, then join or merge the result back into the header table.
  2. Build a sorted/hashed internal table in ABAP with seq_no and item count by looping over gt_item once.
  3. Use READ TABLE ... BINARY SEARCH to find the first matching item row and then count only the matching range.
  4. Use a secondary sorted key on gt_item and LOOP AT gt_item USING KEY ... WHERE seq_no = ...

Which approach would you recommend in real ABAP development?

Is it generally better to push this kind of count aggregation to the database, or is an internal table aggregation preferred when the data is already loaded?

Also, does LOOP AT itab WHERE ... on a standard table benefit from a prior SORT, or should I use a sorted table / secondary key explicitly?

Thanks!

reddit.com
u/Substantial_Half6347 — 3 days ago