Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

Collect with table expressions

jrgkraus
Active Contributor

I like the declarative ABAP style that the table expressions are offering. however, sometimes I have to switch to imperative style because I don't find a solution for the problem. Here's an example. Is this possible using a for expression?

Jörg

Loop at t into l.
  Collect value #(
    Key = l-key
    Val = l-val )
   Into sum.
Endloop.

1 ACCEPTED SOLUTION

nomssi
Active Contributor

GROUP BY

You have to compute the aggregate yourself, something like

LOOP AT t INTO l GROUP BY l-key INTO g.
  APPEND VALUE #( key = g
                  val = REDUCE #( INIT s = 0 FOR i IN GROUP g NEXT s = s + i-val ) ).
ENDLOOP.

or

sum_table = VALUE #( FOR GROUPS g OF l IN t GROUP BY l-key
                 LET total = REDUCE #( INIT s TYPE i FOR i IN GROUP g NEXT s = s + i )
                 IN key = g
                    val = total ).

JNN

5 REPLIES 5

nomssi
Active Contributor

GROUP BY

You have to compute the aggregate yourself, something like

LOOP AT t INTO l GROUP BY l-key INTO g.
  APPEND VALUE #( key = g
                  val = REDUCE #( INIT s = 0 FOR i IN GROUP g NEXT s = s + i-val ) ).
ENDLOOP.

or

sum_table = VALUE #( FOR GROUPS g OF l IN t GROUP BY l-key
                 LET total = REDUCE #( INIT s TYPE i FOR i IN GROUP g NEXT s = s + i )
                 IN key = g
                    val = total ).

JNN

pokrakam
Active Contributor

I think your second version has a bug, it's counting the entire rows. I would go for:

DATA(totals) = VALUE t_total( 
    FOR GROUPS g OF l IN t
    GROUP BY l-key
    LET total = REDUCE #( INIT sum TYPE i
                          FOR  row IN GROUP g
                          NEXT sum = sum + row-value )
    IN  ( key = g
          val = total ) ).

nomssi
Active Contributor

Thanks Mike!

This is a good use case for ABAP Unit. Tests would bring/restore trust in the implementation.

JNN

jrgkraus
Active Contributor
0 Kudos

Thanks for the answer - my missing link was the use of grouping in a reduce expression. All the best.

pokrakam
Active Contributor

+1 to unit testing. It's tempting to think the code is so obvious why do I need to test it, but I know from my own experience these things creep in so easily.