Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgresql extract last row for each group

I have the following data

app people login
slack Jenny 2019-01-01
slack Jenny 2020-01-01
slack Jenny 2021-01-01
slack Yang 2020-06-01
slack Yang 2021-06-01

For each group app and user, I need to get the latest login date. I tried to use a window function, but could not get the result of what I am expecting:

SELECT app, people, LAST_VALUE(login) OVER (PARTITION BY app, people ORDER BY login)
FROM xxxxx

Any suggestions?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the MAX window function in place of the LAST_VALUE window function:

SELECT app, 
       people, 
       MAX(login) OVER (PARTITION BY app, people ORDER BY login DESC)
FROM tab

Check the demo here.


Instead, if you want to aggregate your "app" and "people" values on the last login value, you can also use the MAX aggregation function:

SELECT app, 
       people, 
       MAX(login)
FROM tab
GROUP BY app, 
         people

Check the demo here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading