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
Release: 2025-01-21 06:11:08
Original
502 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template