Development resources, articles, tutorials, code samples, tools and downloads for ASP.Net, SQL Server, Reporting Services, T-SQL, Windows, AWS, SAP HANA and ABAP
SQL - SELECT TOP n or SELECT TOP Random n Rows From a Table For Each Category or Group
You may need a sql query that will select top n records or random n recordsfor each category in a table. The t-sql query that will solve this problem
may be difficult for first timers, especially if you are working on MS SQL
Server 2000. Now, with the t-sql enhancements in Microsoft SQL Server 2005
the problem of selecting a definite number of records grouped or categorized
according to a column is easier to create.
Let's define the problem once more to make you easy to imagine in your mind.
Assume that you have articles categorized by their topics. Say, articles may
be in categories T-SQL, SSAS, SSIS, SSRS, .NET Framework, ASP.NET, VB.NET,
C#, VISTA etc.
You want a t-sql query that will display random 3 records from each available category in the main page of your web site.
After inserting the above records as sample into the Article Categories and Articles by running the above sql code, we are ready for running the first t-sql script.
What is important about the above t-sql select command is that it can also run
on MS SQL Server 2000 successfully.
If you are running SQL Server 2005 or SQL Server 2008 as your database, you can try the following sql select statements also.
Here in this sql select top query, we are using the ROW_NUMBER() OVER (PARTITION BY
columnname ORDER BY DESC) to get the list of articles with a row number grouped
according to the column values, in our sample ArticleCategoryId. This creates a
new numbering starting from 1 for each article category.
An other method of selecting records belonging to different groups or categories can be implemented by using the CROSS APPLY join shown as in the below t-sql select statement.
I think you have noticed that till now we have selected our articles or rows according to an order of column values descending or ascending.
We can further alter the select statements in order to select random records from each group of record by using the ORDER BY CHECKSUM(NEWID())
Here is the updated scripts of sql which fetch random n rows from each category in a table.