问题
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