MySQL为特定类型的c中的每种类型选择特定的行数

时间:2019-03-19 02:29:15

标签: mysql sql database navicat

我想按特定列的组选择前一定数量的行。例如:

原始数据:

  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

我想为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

2 个答案:

答案 0 :(得分:1)

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行,则所有行都将被占用。

答案 1 :(得分:1)

您可以通过在index上自行联接表来获得所需的结果,其中联接表中的index的值小于第一个表中的值,并仅选择具有<具有较低索引值的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