Skip to content
Advertisement

DISTINCT and ORDER BY in the same command without using the order by variable

I need to select the recent 5 games the user has gone into but I don’t want there to be duplicates. So I need a SQL line that will take them in order from most recent to least but also make sure there are no distinct. To order them I have a time variable, but if I use:

this removes all the other times apart from the first ones meaning that I will get the result in the order of which game was played first ever.

If you still don’t understand here is the schema and some of the data I have:

Schema:

Data:

So if you see here if I use distinct on time it won’t work, as everything would still be displayed.

Advertisement

Answer

Use ROW_NUMBER() window function to rank each row of the table based on user and game and ordered by time descending.
From these results keep only the rows with rank = 1, meaning the latest rows for each combination of user and game.
Then use ROW_NUMBER() again to rank the remaining rows based on user and ordered by time descending and from the results keep only the rows with rank <= 5:

If you want results for a specific user it is easier, just use MAX() window function and sort the results to get the top 5 rows:

Or if the image may be different for the same name form row to row:

See the demo.
Results (for your sample data):

userid name image time
6 Arcade Mathematicians arcadeMathematicians 2021-04-17 08:03:21
6 Infinite Spinner infiniteSpinner 2021-04-17 08:03:18
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement