Skip to content

ABAP Keyword Documentation →  ABAP - Reference →  Processing External Data →  ABAP Database Accesses →  Open SQL →  Open SQL - Read Accesses →  SELECT →  SELECT - result →  SELECT - select_list →  SELECT - col_spec →  SELECT - sql_exp →  Examples of SQL Expressions 

SQL Expressions, Use in Aggregate Expressions

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

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 + num2 ) AS max,
           MIN( num1 + num2 ) AS min,
           MIN( num1 * 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 + num2 ) AS max,
           MIN( num1 + num2 ) AS min
           FROM demo_expressions
           GROUP BY char1, char2
           HAVING MIN( num1 * 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, aggregate functions are used to determined aggregated values whose arguments are 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 aggregate expression that has an arithmetic expression as an argument.