Skip to content
Advertisement

MySQL select a certain amout of rows for each type in a certain c

I would like to select the first certain number of rows, by groups of a certain column. For example :

Original data:

I would like to select the first 4 rows for each unique value of type, and the order is by index.

So the ideal result would be:

Advertisement

Answer

row_number() is the typical solution to this:

In older versions of MySQL, you can do:

The coalesce() is so all rows are taken if there are not 4 rows for the type.

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