SQL -Max function

Lets understand MAX function in SQL

Sun Dec 21, 2025

SQL

requirement

Open VBEP table which contains schedule line details for each sales order

Now check which ETENR has value more than 1 or 2 or 3 . its your choice

The expected result is


 SELECT vbeln , MAX( etenr ) AS maxetenr
 FROM vbep
INTO TABLE @DATA(lt_vbep)
WHERE vbeln IN ( '0000000128' ,'0000000204' ,
'0000000214' ,'4000000003' )
 GROUP BY vbeln ORDER BY vbeln.
In the above example we have hardcoded the VBELN numbers.What if we have an internal table for VBELN.In this case we need to use HAVING clause 

SELECT DISTINCT vbeln FROM vbak
INTO TABLE @DATA(lt_vbap)
WHERE vbeln IN ( '0000000128' ,'0000000204' ,
'0000000214' ,'4000000003' )
ORDER BY vbeln.
IF sy-subrc EQ 0.
DATA lr_vbeln TYPE RANGE OF vbeln.
lr_vbeln = VALUE #( FOR ls IN lt_vbap sign = 'I' option = 'EQ'
( low = ls-vbeln ) ).

SELECT vbeln , MAX( etenr ) AS maxetenr
FROM vbep
INTO TABLE @DATA(lt_vbep)
WHERE vbeln IN @lr_vbeln
GROUP BY vbeln
ORDER BY vbeln.
* SELECT vbeln , MAX( etenr ) AS maxetenr
* FROM vbep
* INTO TABLE @DATA(lt_vbep)
* WHERE vbeln IN ( '0000000128' ,'0000000204' ,
* '0000000214' ,'4000000003' )
* GROUP BY vbeln ORDER BY vbeln.
IF sy-subrc EQ 0.

ENDIF.
ENDIF.

LearnABAP.IO
10 plus in ABAP | ex Deloitte | 2X certified  

Insta - abapcafe Telegram - abapcafe Linkedin - learnabap.io