selecting top N rows for each group in a table

后端 未结 3 1179
醉酒成梦
醉酒成梦 2020-11-30 04:03

I am facing a very common issue regarding \"Selecting top N rows for each group in a table\".

Consider a table with id, name, hair_colour, score columns

3条回答
  •  忘掉有多难
    2020-11-30 04:55

    Use this compound select which handles OP problem properly

    SELECT g.* FROM girls as g
    WHERE g.score > IFNULL( (SELECT g2.score FROM girls as g2
                    WHERE g.hair=g2.hair ORDER BY g2.score DESC LIMIT 3,1), 0)
    

    Note that you need to use IFNULL here to handle case when table girls has less rows for some type of hair then we want to see in sql answer (in OP case it is 3 items).

提交回复
热议问题