Home > OS >  ABAP - Group employees by cost center and calculate sum
ABAP - Group employees by cost center and calculate sum

Time:12-10

I have an internal table with employees. Each employee is assigned to a cost center. In another column is the salary. I want to group the employees by cost center and get the total salary per cost center. How can I do it?

At first I have grouped them as follows:

Loop at itab assigning field-symbol(<c>) 
group by <c>-kostl ascending.

Write: / <c>-kostl.

This gives me a list of all cost-centers. In the next step I would like to calculate the sum of the salaries per cost center (the sum for all employees with the same cost-center).

How can I do it? Can I use collect?

Update: I have tried with the follwing coding. But I get the error "The syntax for a method specification is "objref->method" or "class=>method"". lv_sum_salary = sum( <p>-salary ).

loop at i_download ASSIGNING FIELD-SYMBOL(<c>)
    GROUP BY <c>-kostl ascending.
    Write: / <c>-kostl, <c>-salary.

    data: lv_sum_salary type p DECIMALS 2.
    Loop at group <c> ASSIGNING FIELD-SYMBOL(<p>).
    lv_sum_salary = sum( <p>-salary ).
     Write: /'  ',<p>-pernr,  <p>-salary.
    endloop.
     Write: /'  ', lv_sum_salary.
  endloop.

CodePudding user response:

I am not sure where you got the sum function from, but there is no such build-in function. If you want to calculate a sum in a group-by loop, then you have to do it yourself.

" make sure the sum is reset to 0 for each group
CLEAR lv_sum_salary.
" Do a loop over the members of this group
LOOP AT GROUP <c> ASSIGNING FIELD-SYMBOL(<p>).
  " Add the salary of the current group-member to the sum
  lv_sum_salary = lv_sum_salary   <p>-salary.
ENDLOOP.
" Now we have the sum of all members
WRITE |The sum of cost center { <c>-kostl } is { lv_sum_salary }.|.
  • Related