What is the best way to select the first two records of each group by a “SELECT” command?

后端 未结 3 711
别跟我提以往
别跟我提以往 2021-02-10 05:30

For instance I have the following table:

id group data
1 1 aaa
2 1 aaa
3 2 aaa
4 2 aaa
5 2 aaa
6 3 aaa
7 3 aaa
8 3 aaa

What is the best way to

3条回答
  •  执笔经年
    2021-02-10 05:50

    select a.*
    from Tablename a
    where 
    (
       select count(*) 
       from Tablename as b
       where a.group = b.group and a.id >= b.id
    ) <= 2
    
    • SQLFiddle Demo

提交回复
热议问题