Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

SQL: retrieve the most recent entry

tafkap95
Participant
0 Kudos
297

Hello,

I would like to retrieve the most recent entry of my data table at once.

Let's imagine I have the following table (a piece of the MSEG table):

 

ROWSMATNRCHARGCPU_DATECPU_TIME
1000012345CA00109.16.202414:00:00
2000012345CA00209.16.202415:12:12
3000012345BO25603.03.202423:12:00
4000012345CU12309.17.202400:34:37
5000012345RA69827.06.202408:00:00
6000065887TT000123.03.202305:32:00
7000065887YU365401.01.202407:12:00
8000065887PP554627.12.202315:23:00

For article 000012345 I wanted to retrieve line 4 from an internal table and for article 000065887 line 7, which are the most recent records by comparison of the CPU_DATE/CPU_TIME fields.

Thanks for any help.

 

3 REPLIES 3

raymond_giuseppi
Active Contributor
267

What did you already try, some subquery or ?

SELECT matnr, charg, cpudt_mkpf, cputm_mkpf
       FROM mseg AS m
       WHERE m~cpudt_mkpf EQ 
           ( SELECT MAX( cpudt_mkpf ) FROM mseg WHERE matnr EQ m~matnr )
         AND m~cputm_mkpf EQ 
           ( SELECT MAX( cputm_mkpf ) FROM mseg WHERE matnr EQ m~matnr AND cpudt_mkpf = m~cpudt_mkpf )
       INTO CORRESPONDING FIELDS OF TABLE @mytab.

 

Sandra_Rossi
Active Contributor
263

Modern way (>= 7.54): window expression - ABAP Keyword Documentation (sap.com).

There's still the older way (join on itself via EXISTS, take MAX), simplified version: SELECT matnr, cpudate FROM mseg AS alias WHERE EXISTS IN ( SELECT matnr, MAX(cpudate) FROM mseg GROUP BY matnr WHERE matnr = alias~matnr).

0 Kudos
191

Hi Sandra, 

I really like the idea of the Modern Way, it's always interesting to learn new features, I'll take a closer look at that.