Make math operations on a grouped table

一笑奈何 提交于 2019-12-02 15:08:50

问题


My problem is not in a real programming Language.

I have an exercise in ABAP Language but is not very important the language.

Anyway, I have a table:

I need to make the total cost of the position(after the select obviously). Then, the table will be grouped by two fields (MATNR and BUKRS), so I need to know for each Group the total cost MAX, the total cost MIN and the total cost AVERAGE of the positions.

However I need a simple algorithm to solve this problem (pseudo-code).

I hope I was clear.


回答1:


For table aggregations I find the AT functions within a LOOP very handy.

Sort your fields according the dimensions you need and sort the values within ascending or descending.

The order of the fields is very important here, because the AT looks for changes in the specified field and all fields left of it in the same row. So you handle group for group and append the result of the group aggregation to your result table.

LOOP AT lt_itab ASSIGNING <ls_itab>.
  AT NEW bukrs. "at first entry of combination matnr, bukrs
    ls_agg-matnr = <ls_itab>-matnr.
    ls_agg-bukrs = <ls_itab>-bukrs.
  ENDAT.

  TRY.
    ADD <ls_itab>-amount TO lf_sum.
  CATCH cx_sy_arithmetic_overflow.
     lf_sum = 9999.
  ENDTRY.

  lf_count = lf_count + 1.
  IF <ls_itab>-amount > lf_max.
     lf_max = <ls_itab>-amount.
  ENDIF.

  AT END OF bukrs. "after last entry of combination matnr,bukrs
    ls_agg-avg = lf_sum / lf_count.
    ls_agg-max = lf_max.
    APPEND ls_agg TO lt_agged.
    CLEAR: ls_agg, lf_sum, lf_count, lf_max.
  ENDAT.
ENDLOOP.


来源:https://stackoverflow.com/questions/39458368/make-math-operations-on-a-grouped-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!