Search code examples
sumabap

Calculate Sum based on condition


How to do summation in the internal table with condition?

For example, my itab have the following data:

itab l_bcode_i :

vgpos[1] :10 , menge[1]:600

vgpos[2] :10 , menge[2]:500

vgpos[3] :20 , menge[3]:400

vgpos[4] :20 , menge[4]:300

vgpos[5] :30 , menge[5]:200

vgpos[6] :30 , menge[6]:10

The requirement request to sum up the data with the same vgpos number by using the menge, and use to display another message.

I try to show

vgpos: 10 menge = 1100

vgpos:20 menge = 500

vgpos:30 menge = 210

I try to use loop and sum, however the result not as the result I need because it will total up all the menge value by ignored the where clause condition that I set. Any recommendation or suggestion is appreciated:

at last, it should menge = 1810

LOOP AT LT_BCODE_I INTO LT_BCODE_I WHERE VGPOS = LW_LIPS2-VGPOS.
        AT LAST.
          SUM.
          cl_demo_output=>display( LT_BCODE_I-MENGE ).
        ENDAT.
      ENDLOOP.

Solution

  • Hi I able to fixed my problem by using the following code:

    In stead of At Last, I change to use the AT END. After used the AT END, I able to get the result I need.

    LOOP AT LT_BCODE_I INTO LT_BCODE_I WHERE VGBEL = LT_LIPS-VGBEL AND VGPOS = LT_LIPS-VGPOS.
            AT END OF VGBEL.
              SUM.
              LT_BCODE_I-MENGE = LT_BCODE_I-MENGE .
            ENDAT.
          ENDLOOP.