HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to get latest 2 records of each group

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
latesteachgrouprecordsgethow

Problem

So, I have table similar to:

sn color value
1  red   4
2  red   8
3  green 5
4  red   2
5  green 4
6  green 3


Now I need the latest 2 rows for each color, eg:

2  red   8
4  red   2
5  green 4
6  green 3


How to do it, other than using separate query for each color?

Thanks

Solution

With MySQL 8

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.