Friday, March 20, 2009

SQL: Randomly Select One Record from Multiple Categories

This query will randomly select one record from multiple categories that you specify. First the inner select partitions the record set based on a specific field, then order's it randomly by using newid(). The outer select then selects the top row from each category (aka the partioned group). The top record is always random due ordering by newid().

SELECT * FROM (
SELECT
ROW_NUMBER() OVER(PARTITION BY a.Category ORDER BY newid()) AS RowNumber,
*
FROM Table a ) b
WHERE RowNumber = 1

No comments: