Search code examples
abapopensql

GROUP by aggregation does not calculate SUM


I have to aggregate in my query SUM of AMUNT field according to WERKS, DATUM and UZEIT I try to make a group by without any success I have an error like that:enter image description here

What is the problem in my code?

That is my ABAP code:

 DATA: gt_compr TYPE TABLE OF yrt_h_sales
 SELECT    werks, extnb, datum, uzeit, sumvt, deprt, dpext, SUM( amunt ) AS amunt
  INTO      CORRESPONDING FIELDS OF TABLE @gt_compr
  FROM      yrt_h_sales 
  WHERE     werks IN @so_werks
  AND       datum IN @so_datum
  GROUP BY  werks, datum, uzeit.

After I corrected it and I did this, the code looks as follows:

 SELECT    werks,  datum, uzeit, extnb, deprt, dpext, SUM( amunt ) AS amunt
  INTO      CORRESPONDING FIELDS OF TABLE @gt_compr
  FROM      yrt_h_sales
  WHERE     werks IN @so_werks
  AND       datum IN @so_datum
  GROUP BY  werks, datum, uzeit,  extnb, deprt, dpext.

So I don't have the compilation error anymore but the aggregation is still not working! I have a 43 line result without sum on the AMUNT column

P.S. this is the structure of my table: enter image description here


Solution

  • Your observation is consistent with the documentation (and what I have so far seen in any other RDBMS I've worked with):

    If aggregate expressions are used, any column identifiers that are not included as arguments of an aggregate function must be included after the addition GROUP BY.

    Take for example the time field UZEIT: You can tell the system to aggregate (in your case, sum up) all amounts for the same point in time by adding it to the GROUP BY clause, or you can apply an aggregate function as well (SUM would not make any sense here, but MIN might), or you could omit the field altogether. You can not leave it dangling around without further specification - the field either needs to be part of the new key set created by GROUP BY or has to have an aggregate function applied to it so that the system knows what to do with multiple datasets that might occur in the group.

    (This is basic SQL btw and not ABAP-specific knowledge.)