Home >Database >Mysql Tutorial >How to Efficiently Query Top N Records Across Multiple Categories in SQL?

How to Efficiently Query Top N Records Across Multiple Categories in SQL?

Susan Sarandon
Susan SarandonOriginal
2025-01-21 06:11:08474browse

How to Efficiently Query Top N Records Across Multiple Categories in SQL?

Retrieving Top N Records from Multiple Categories in SQL

This SQL technique efficiently retrieves the top N records (e.g., top 10) from various categories within a single table.

<code class="language-sql">SELECT rs.Field1, rs.Field2
FROM (
    SELECT Field1, Field2,
    RANK() OVER (PARTITION BY Section ORDER BY RankCriteria DESC) AS Rank
    FROM table
) rs
WHERE Rank <= 10;</code>

Explanation:

  • Field1 and Field2: These represent the columns you want to retrieve.
  • The inner SELECT statement uses the RANK() window function. PARTITION BY Section divides the data into groups based on the 'Section' category. ORDER BY RankCriteria DESC sorts records within each section by your ranking criteria in descending order. Rank assigns a rank to each record within its section.
  • The outer SELECT statement filters the results, keeping only records with a Rank value of 10 or less (Rank <= 10).

This method is efficient and works even on database systems that may lack dedicated row-limiting functions. It's ideal when performance is critical.

The above is the detailed content of How to Efficiently Query Top N Records Across Multiple Categories in SQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn