Skip to content
Advertisement

How to SELECT two records for each unique column value as one row in MySQL?

I have a MySQL table like this :

What I try is to output for each unique GID value their p1, p10, p100 of the two last most recent createdAt

Output example :

I tried to use subqueries to achieve my goal but I am not confortable with that.

Thank you to anyone who can provide me informations and help.

Advertisement

Answer

You would use lag() for this:

Here is a db<>fiddle.

The subquery returns the previous values for each column. The outer query simply filters down to the most recent row for each gid/name combination.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement