MySQL select 特定 c 中每种类型的特定行数

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

我想select第一定行数,按某列分组。例如:

原始数据:

  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

我想 select 每个唯一值 type 的前 4 行,顺序是 index.

所以理想的结果是:

      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

row_number() 是典型的解决方案:

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

在旧版本的 MySQL 中,您可以:

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
                          );

coalesce() 是这样的,如果该类型没有 4 行,则将获取所有行。

您可以通过在 index 上自行加入您的 table 来获得您想要的结果,其中加入的 table 中的 index 的值小于 table 中的值第一个,只选择那些索引值小于 4 的行:

SELECT t1.id, t1.index, t1.type, t1.value
FROM test t1
LEFT JOIN test t2 ON t2.index < t1.index AND t2.type = t1.type
GROUP BY t1.id, t1.index, t1.type, t1.value
HAVING COUNT(t2.index) < 4

输出:

id  index   type    value
0   1       a       0.71643
1   2       a       0.22365
2   3       a       0.375417
3   4       a       0.773874
6   7       b       0.377718
7   8       b       0.487772
8   9       b       0.672767
9   10      b       0.275895
13  14      c       0.347563
14  15      c       0.101106
15  16      c       0.390205
16  17      c       0.235941

Demo on dbfiddle