Aggregates, GROUP BY and HAVING
Use database aggregation instead of fetching all rows and calculating totals in ABAP.
Explanation
Aggregation means calculating totals, counts, minimums, maximums or averages. In many cases, it is better to let the database perform aggregation using SUM, COUNT, MIN, MAX and GROUP BY instead of fetching all records into ABAP and looping to calculate totals. This is especially important in S/4HANA and HANA-based systems, where database pushdown can reduce memory and network transfer. HAVING is used to filter grouped results after aggregation. The key is to aggregate at the right level. If the report needs total billing value by customer, fetch grouped totals instead of every item row unless item-level detail is required.
Code example
SELECT kunag AS customer, SUM( netwr ) AS total_value, COUNT( * ) AS invoice_count FROM vbrk WHERE fkdat BETWEEN @p_from AND @p_to GROUP BY kunag HAVING SUM( netwr ) > 100000 INTO TABLE @DATA(lt_customer_total).Real project scenario
A business wants total billing amount by customer for a month. Instead of selecting all billing items and calculating totals in ABAP, the query groups by customer and sums net value at database level.
Common mistakes
- Fetching all rows and aggregating in ABAP unnecessarily. - Missing GROUP BY fields. - Using HAVING when WHERE should be used. - Aggregating at the wrong business level.
Best practices
- Use database aggregation for large datasets. - Use WHERE for pre-aggregation filters. - Use HAVING for aggregate result filters. - Aggregate only at the business-required level.
Interview angle
A strong candidate should explain that WHERE filters before grouping, while HAVING filters after aggregation.