Open SQL Part 6: Aggregates, GROUP BY and HAVING
Lessons are open to try during our launch period. Some advanced content may move to Pro later. AI practice limits apply separately.
Let the database compute totals: COUNT, SUM, MIN, MAX, AVG, GROUP BY and HAVING, DISTINCT, and summing amounts correctly per currency — instead of loops and COLLECT in ABAP.
In this lessonShow sectionsHide sections
Visual overview
Expert visual walkthrough
Aggregates, GROUP BY and HAVING
Open SQL · Chapter-specific technical teaching map
Integration path
Group key
COUNT / SUM
HAVING condition
Result
Tutor's chapter takeaway
Let the database compute totals: COUNT, SUM, MIN, MAX, AVG, GROUP BY and HAVING, DISTINCT, and summing amounts correctly per currency — instead of loops and COLLECT in ABAP.
In a real project
A monthly revenue report read all bookings of the year (8 million rows) and summed them in ABAP with COLLECT. It needed 40 minutes, and the totals mixed EUR and USD amounts in one column, which nobody noticed because the…
Watch out for
• Summing in ABAP what the database can aggregate. • Summing across currencies or units. • Selecting non-aggregated fields missing from GROUP BY. • Using HAVING where WHERE should filter rows. • Expecting aggregates to use…
The situation: a real project scenario
A monthly revenue report read all bookings of the year (8 million rows) and summed them in ABAP with COLLECT. It needed 40 minutes, and the totals mixed EUR and USD amounts in one column, which nobody noticed because the numbers looked plausible.
Rewriting the logic as SUM … GROUP BY airline, month and currency reduced runtime to seconds and exposed the currency mix; the output was changed to show one line per currency.
Explanation
Parts 1 through 5 of this series focused on reading rows; often, though, all you actually need are numbers — seats per airline, revenue per month — and the database computes these far faster than a loop in ABAP ever could. The aggregate functions available are COUNT( * ) for the number of rows, COUNT( DISTINCT f ) for the number of distinct values in a field, and SUM, MIN, MAX, and AVG; AVG returns a float-like result, so it needs care when used on amounts.
GROUP BY groups the aggregation: SELECT carrid SUM( seatsocc ) FROM sflight INTO TABLE gt_seats GROUP BY carrid. groups by carrier. Every selected field that isn't itself aggregated must appear in the GROUP BY clause, and the target structure must match the selected columns — in strict syntax, give the aggregate an alias, such as SUM( seatsocc ) AS occupied.
HAVING filters the groups themselves, after aggregation has happened — for example … GROUP BY carrid HAVING SUM( seatsocc ) > 10000. WHERE, by contrast, runs first and decides which rows go into the groups in the first place; HAVING runs afterward and decides which groups remain in the result.
Currencies and units need particular care: summing forcuram across EUR and USD bookings is meaningless, since you'd be adding two different currencies together as if they were the same number — always GROUP BY the currency field (forcurkey) as well, or convert everything to one currency first. The same logic applies to quantities and their units.
Aggregate statements bypass the table buffer entirely. That's fine for large tables, but for small, buffered tables, it may actually be worth reading the rows and summing them in ABAP instead, since the buffer would otherwise be bypassed for no real benefit.
The reason to do this in the database at all: reading 2 million bookings just to sum them in ABAP transfers all 2 million rows to the application server, while SUM … GROUP BY transfers only a few dozen result rows. On HANA, this kind of aggregation is extremely fast, thanks to its column store.
To practice, run the code example covering bookings per airline, revenue per airline and currency, airlines with more than N bookings using HAVING, and a count of distinct customers. By the end, you should be computing totals in SQL, and never summing across currencies.
Code example
REPORT zosql_part6. TYPES: BEGIN OF ty_rev, carrid TYPE s_carr_id, forcurkey TYPE s_curr, revenue TYPE s_f_cur_pr, bookings TYPE i, END OF ty_rev, BEGIN OF ty_busy, carrid TYPE s_carr_id, bookings TYPE i, END OF ty_busy, BEGIN OF ty_range, carrid TYPE s_carr_id, connid TYPE s_conn_id, first_flight TYPE s_date, last_flight TYPE s_date, END OF ty_range. DATA: gt_rev TYPE STANDARD TABLE OF ty_rev, gs_rev TYPE ty_rev, gt_busy TYPE STANDARD TABLE OF ty_busy, gt_cust TYPE STANDARD TABLE OF ty_busy, gt_range TYPE STANDARD TABLE OF ty_range, gv_cnt TYPE i. START-OF-SELECTION.* ===== 1. Count rows ===== SELECT COUNT( * ) FROM sbook INTO gv_cnt WHERE carrid = 'LH'. " COUNT runs in the DB -> no rows transferred to ABAP at all WRITE: / 'LH bookings:', gv_cnt. * ===== 2. SUM per airline AND currency ===== SELECT carrid forcurkey SUM( forcuram ) COUNT( * ) FROM sbook INTO TABLE gt_rev WHERE cancelled = space GROUP BY carrid forcurkey. " currency in GROUP BY! summing mixed currencies as one number would be meaningless LOOP AT gt_rev INTO gs_rev. WRITE: / gs_rev-carrid, gs_rev-revenue CURRENCY gs_rev-forcurkey, gs_rev-forcurkey, gs_rev-bookings. ENDLOOP. * ===== 3. HAVING: only airlines with many bookings ===== SELECT carrid COUNT( * ) FROM sbook INTO TABLE gt_busy WHERE cancelled = space GROUP BY carrid HAVING COUNT( * ) > 1000. " HAVING filters on the aggregated result; WHERE can't reference COUNT(*) * ===== 4. Distinct customers per airline ===== SELECT carrid COUNT( DISTINCT customid ) FROM sbook INTO TABLE gt_cust GROUP BY carrid. " DISTINCT inside COUNT removes duplicate customer IDs before counting * ===== 5. Earliest and latest flight date per connection ===== SELECT carrid connid MIN( fldate ) MAX( fldate ) FROM sflight INTO TABLE gt_range GROUP BY carrid connid. * AVOID: SELECT * FROM sbook INTO TABLE gt_all. LOOP ... COLLECT ... ENDLOOP.* -> millions of rows transferred just to compute a few totals* 💡 Strict syntax adds aliases: SELECT carrid, COUNT( * ) AS bookings ... INTO TABLE @DATA(lt_busy).Watch out
Common mistakes
- Summing in ABAP what the database can aggregate.
- Summing across currencies or units.
- Selecting non-aggregated fields missing from GROUP BY.
- Using HAVING where WHERE should filter rows.
- Expecting aggregates to use the table buffer.
Do this
Best practices
- Aggregate in SQL; transfer only results.
- Always group by currency/unit for amounts/quantities.
- Filter rows with WHERE, groups with HAVING.
- Use aliases and matching target structures.
- Test with multi-currency data.
In the interview
Interview angle
Questions: "WHERE vs HAVING?", "Why aggregate in the database?", "What must be in GROUP BY?"
Strong answer: WHERE filters rows before grouping, HAVING filters groups after aggregation; all non-aggregated selected fields must be in GROUP BY; aggregating in the DB avoids transferring millions of rows (especially fast on HANA); always group amounts by currency; aggregates bypass the buffer.
Practice this lesson
Quick check
0 of 3 questions attempted
Question 1 of 3
Which clause filters groups after aggregation?
Question 2 of 3
A query sums booking amounts per airline. Which GROUP BY is correct?
Question 3 of 3
Aggregate functions like SUM/COUNT require:
Practise this in an interview
Answer in your own words and get instant feedback, the way an interviewer would judge it.
1Explain the GROUP BY and HAVING clauses in Open SQL. Provide an example that counts orders by customer and filters for customers with > 10 orders.
2Explain aggregate functions in Open SQL (SUM, COUNT, AVG, MAX, MIN) and how they work with GROUP BY. Include how to handle NULL values.
Try a related Code Lab
This published exercise covers the same SAP topic. Apply the ideas in a hands-on scenario, then return to review your answers.
Open: FOR ALL ENTRIES with an empty driver table →See it in code
Each example starts from a requirement, shows the design, then the code step by step with a plain-language explanation of every part.
- Let the database add up: GROUP BY, SUM, HAVING and a size label on sales items (VBAP)
- ABAP SQL: create a table, then insert, read, update and delete rows
- Modern ABAP: total per customer with VALUE, FOR, GROUP BY, REDUCE and an ABAP Unit test
- ABAP SELECT: FOR ALL ENTRIES versus INNER JOIN (and its three traps)
Was this lesson helpful?
Keep exploring
Interview questions on this topic
Related SAP topics
Check before use: lesson examples are educational, not a guarantee of correctness for your SAP edition or release. Sample code has not been executed on your SAP system. Confirm API availability, syntax, authorizations and business impact in an approved development or test environment.