Select top 10 records for each category

前端 未结 14 1404
别那么骄傲
别那么骄傲 2020-11-22 04:27

I want to return top 10 records from each section in one query. Can anyone help with how to do it? Section is one of the columns in the table.

Database is SQL Serve

14条回答
  •  暖寄归人
    2020-11-22 05:16

    While the question was about SQL Server 2005, most people have moved on and if they do find this question, what could be the preferred answer in other situations is one using CROSS APPLY as illustrated in this blog post.

    SELECT *
    FROM t
    CROSS APPLY (
      SELECT TOP 10 u.*
      FROM u
      WHERE u.t_id = t.t_id
      ORDER BY u.something DESC
    ) u
    

    This query involves 2 tables. The OP's query only involves 1 table, in case of which a window function based solution might be more efficient.

提交回复
热议问题