How to use GROUP-BY clause in SAP ABAP

The values of a column can be grouped by using the GROUP BY statement. The GROUP BY clause must always come at the end of the ‘SELECT’ statement. It should always be after the ‘FROM’ clause and ‘WHERE’ clause.

Let us consider an example, where we group all the contact based on contact address.

DATA lt_contact TYPE TABLE OF ztt_db_table2.

SELECT contact_name contact_address FROM ztt_db_table2 INTO TABLE lt_contact

GROUP BY contact_name contact_address HAVING contact_address = ‘Street 12’.

The columns mentioned after ‘SELECT’ keyword must match the columns mentioned after ‘GROUP BY’ keyword. In the above query, we have used additional constraint using the ‘HAVING’ keyword.

The results are grouped based on the columns contact_name and contact_address. So these column names are mentioned exactly after the ‘SELECT’ and ‘GROUP BY’ keyword. The additional constraint such as contact_address = ‘Street 12’ through HAVING option will help us to further filter the data records with street address equal to ‘Street 12’.