Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select top 10 records for each category

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 Server 2005. I want to return the top 10 by date entered. Sections are business, local, and feature. For one particular date I want only the top (10) business rows (most recent entry), the top (10) local rows, and the top (10) features.

like image 583
jbcedge Avatar asked Oct 07 '08 02:10

jbcedge


People also ask

How do you select Top 10 records from each category in SQL?

Selecting a top n records for each category from any table, can be done easily using row_number function which generates a sequential integer to each row within a partition of a result set.

How do you write top 10 records in SQL?

Example - Using TOP PERCENT keywordSELECT TOP(10) PERCENT employee_id, last_name, first_name FROM employees WHERE last_name = 'Anderson' ORDER BY employee_id; This SQL Server SELECT TOP example would select the first 10% of the records from the full result set.

How do I select the top 10 rows in a table?

For example, TOP(10) would return the top 10 rows from the full result set. Optional. If PERCENT is specified, then the top rows are based on a percentage of the total result set (as specfied by the top_value).

How do I select top 10 rows in MySQL?

To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement. Here is the alternate query to select first 10 elements.


1 Answers

If you are using SQL 2005 you can do something like this...

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 

If your RankCriteria has ties then you may return more than 10 rows and Matt's solution may be better for you.

like image 159
Darrel Miller Avatar answered Oct 12 '22 05:10

Darrel Miller