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:

  index   type     value
0       1    a  0.716430
1       2    a  0.223650
2       3    a  0.375417
3       4    a  0.773874
4       5    a  0.802127
5       6    a  0.956563
6       7    b  0.377718
7       8    b  0.487772
8       9    b  0.672767
9      10    b  0.275895
10     11    b  0.981751
11     12    b  0.914780
12     13    b  0.940582
13     14    c  0.347563
14     15    c  0.101106
15     16    c  0.390205
16     17    c  0.235941
17     18    c  0.593234
18     19    c  0.904659

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:

      index    type    value
0       1.0      a  0.716430
1       2.0      a  0.223650
2       3.0      a  0.375417
3       4.0      a  0.773874
4       7.0      b  0.377718
5       8.0      b  0.487772
6       9.0      b  0.672767
7      10.0      b  0.275895
8      14.0      c  0.347563
9      15.0      c  0.101106
10     16.0      c  0.390205
11     17.0      c  0.235941

Advertisement

Answer

row_number() is the typical solution to this:

select t.*
from (select t.*,
             row_number() over (partition by type order by index) as seqnum
      from t
     ) t
where seqnum <= 4;

In older versions of MySQL, you can do:

select tm.*
from telegram_message tm
where tm.index <= coalesce( (select tm2.index
                             from telegram_message tm2
                             where tm2.type = tm.type
                             order by tm2.index asc
                             limit 1 offset 3
                            ), tm.index
                          );

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