Tuesday, October 6, 2015

Multiple Random Selected Rows From A Table (SQL)

This weekend  I was asked to pull random sample of 40 rows.  I was thinking that was super easy, but then they put a kink in the request. They wanted the 40 random rows with 20 from type 'A' and 20 from type 'B' from a specific table (TableName) in Microsoft SQL Server. The first was 20 random people where ColumnName = 'A' and the second was 20 random people where ColumnName = 'B'.

Using SQL To Select Random Rows From A Table as a stepping off point.  I have altered the code below to use multiple random SELECT  with a UNION in SQL to accomplish the task.  Easy as pie.

Microsoft SQL Server:
SELECT * FROM 
(SELECT TOP 20 * FROM TableName 
WHERE ColumnName = 'A'
ORDER BY NEWID())
A
Union
SELECT * FROM 
(SELECT TOP 20 * FROM TableName
WHERE ColumnName = 'B'
ORDER BY NEWID())
B


If you like this post and want to see more, follow me on my website www.chadcompton.com Or if you prefer...