snippetsqlMinor
How to get latest 2 records of each group
Viewed 0 times
latesteachgrouprecordsgethow
Problem
So, I have table similar to:
Now I need the latest 2 rows for each color, eg:
How to do it, other than using separate query for each color?
Thanks
sn color value
1 red 4
2 red 8
3 green 5
4 red 2
5 green 4
6 green 3Now I need the latest 2 rows for each color, eg:
2 red 8
4 red 2
5 green 4
6 green 3How to do it, other than using separate query for each color?
Thanks
Solution
With MySQL 8
Using MySQL < 8
You need to use their special variables.. something like this
SELECT sn, color, value
FROM (
SELECT
sn,
color,
value,
DENSE_RANK() OVER (PARTITION BY color ORDER BY sn) AS r
FROM table
) AS t
WHERE t.r <= 2;Using MySQL < 8
You need to use their special variables.. something like this
Code Snippets
SELECT sn, color, value
FROM (
SELECT
sn,
color,
value,
DENSE_RANK() OVER (PARTITION BY color ORDER BY sn) AS r
FROM table
) AS t
WHERE t.r <= 2;Context
StackExchange Database Administrators Q#198697, answer score: 3
Revisions (0)
No revisions yet.