Skip to content

ABAP Keyword Documentation →  ABAP − Reference →  Processing External Data →  ABAP Database Access →  ABAP SQL →  ABAP SQL - Operands and Expressions →  ABAP SQL - SQL Expressions sql_exp →  sql_exp - sql_agg →  ABAP SQL - Examples of Aggregate Expressions 

SQL Expressions, Aggregate Expressions in SQL Expressions

This example demonstrates aggregate expressions as an argument of SQL expressions.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    DATA(out) = cl_demo_output=>new( ).

    SELECT char1, char2, num1, num2, num1 + num2 AS sum,
                                    num1 * num2 AS product
           FROM demo_expressions
           ORDER BY char1, char2
           INTO TABLE @DATA(ungrouped).
    out->write( ungrouped ).

    SELECT char1 && '_' && char2 AS group,
           MAX( num1 ) + MAX( num2 ) AS max,
           MIN( num1 ) + MIN( num2 ) AS min,
           MIN( num1 ) * MIN( num2 ) AS min_product
           FROM demo_expressions
           GROUP BY char1, char2
           ORDER BY group
           INTO TABLE @DATA(grouped).
    out->write( grouped ).

    SELECT char1 && '_' && char2 AS group,
           MAX( num1 ) + MAX( num2 ) AS max,
           MIN( num1 ) + MIN( num2 ) AS min
           FROM demo_expressions
           GROUP BY char1, char2
           HAVING MIN( num1 ) * MIN( num2 ) > 25
           ORDER BY group
           INTO TABLE @DATA(grouped_having).
    out->write( grouped_having ).

    out->display(  ).

Description

The database table DEMO_EXPRESSIONS is filled with random values in the static constructor.

  • The first SELECT statement reads the filled columns individually. Here, the total and the product of the numeric columns NUM1 and NUM2 are calculated using arithmetic statements in the SELECT list.
  • The second SELECT statement performs a grouping by the columns CHAR1 and CHAR2. For each group, aggregated values whose arguments are aggregate expressions are determined using arithmetic expressions.
  • The third SELECT statement performs the same grouping as the second SELECT statement, but restricts the selected groups using a HAVING clause in which a condition is set on an arithmetic expression that has aggregate expressions as arguments.

See also the executable example for using SQL expression in aggregate expressions. Here, the roles of the expressions are switched and different results are produced.