Application Development and Automation 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: 
Read only

Loop at .....group by

0 Likes
1,832

I have to do SUM HSL field based on blart(doc types).Belnr is key field. There are 3 different document types(BLART).How can i add using loop and group by/ SUM.

2 REPLIES 2
Read only

ThorstenHoefer
Active Contributor
1,694

Hi,

dependent on your version, you can select directly from an internal table like:

select 
    sum( d~hsl ) as HSL
   , d~BLART
from @it_data as d
group by d~BLART
into table @data(lt_result)

or

data: lt_result type hashed table of xxx with unique key BLART,
      lt_data type table of xxx,
      wa_data like line of lt_data.

loop at lt_data into wa_data.
   read table lt_result assigning field-symbol(<wa_result>) 
   with table key blart = wa_data-blart.
   if sy-subrc is initial.
    add wa_data-hsl to <wa_result>-hsl.
  else.
    insert wa_data into table lt_result.
  endif.
endloop.

or

types: begin of ty_data,
       grp type c length 4,
       cnt type int4,
       val type n length 3,
  end of ty_data.


  data: lt_data    type table of ty_data with EMPTY KEY,
        lt_result  like lt_data.

  lt_data = value #(
     ( grp = 'GRP1' val = 4 )
     ( grp = 'GRP1' val = 2 )
     ( grp = 'GRP1' val = 1 )
     ( grp = 'GRP2' val = 3 )
     ( grp = 'GRP2' val = 2 )
     ( grp = 'GRP3' val = 5 )
     ( grp = 'GRP3' val = 8 )
   ).

   lt_result = VALUE #(  FOR GROUPS ls_grp OF wa IN lt_data
                                GROUP BY
                                (
                                   grp =  wa-grp
                                   cnt =  GROUP SIZE
                                )
                           (
                             grp = ls_grp-grp
                             cnt = ls_grp-cnt
                             val = reduce #( init x = 0 for wa1 in group ls_grp  
                                             next  x = x + wa1-val )
                           )
                       ).

Read only

former_member9115
Participant
0 Likes
1,694

Hi,

Try Reduce .

One of the good information is here. Reduce

Also Can try following way.:

Simple example :-

SELECT a~NTGEW , a~WBELN , a~CONTRACT FROM WBRP as a
  FOR ALL ENTRIES IN @lt_bkpf_bseg
      WHERE a~WBELN  = @lt_bkpf_bseg-AWKEY+0(10)
      AND   a~CONTRACT = @lt_bkpf_bseg-NUM+0(10)
      INTO TABLE @DATA(LT_WBRP). 


lv_NTGEW =  REDUCE #( INIT I TYPE NTGEW
                                    FOR W IN LT_WBRP   "internal table
                                    WHERE ( CONTRACT = <lfs_header>-num+0(10)  AND
                                            WBELN = <lfs_header>-AWKEY+0(10)
                                            )
                                    NEXT I = I + W-NTGEW ).