SQL - Give me 3 hits for each type only

前端 未结 4 1548
名媛妹妹
名媛妹妹 2020-12-09 12:53

I have some kind of impossible request :).

I have a table where one of the columns is named type. I would like to SELECT 3 records for each type in tha

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 13:23

    When the table is large and collection is more unpredictable, the row numbering needs to be ordered by type in the inner query for the side-effecting variables to work.

    select id, title, type
    from (select id, title, type,
            @r := CASE WHEN @g = type THEN @r+1 ELSE 1 END r,
            @g := type
          from tbl
          order by type, title) as x
    where row_number <= 3
    # order by type, title
    

    Another way to do this without using side effecting variables, if no two records are exactly the same on (title, type, id), is given below. This uses only standard ANSI SQL92 SQL. It may be slower than the above though.

    select A.id, A.title, A.type
    from tbl A
    left join tbl B on
       A.title = B.title and
       (A.type < B.type or
       (A.type = B.type and A.id < A.id))
    group by A.id, A.title, A.type
    having count(B.title) <= 2
    

提交回复
热议问题