I’ve been struggling with this one SQL query requirement today that I was wondering if someone could help me with.
I have a table of sports questions. One of the columns is the team related to the question. My requirement is to return a set number of random questions where the teams are unique.
So lets say we have the following table and want 5 questions:
Question Answer Team ----------------------------------- question 1 answer 1 team A question 2 answer 2 team B question 3 answer 3 team B question 4 answer 3 team D question 5 answer 3 team A question 6 answer 3 team C question 7 answer 3 team F question 8 answer 3 team C question 9 answer 3 team G question 10 answer 3 team D
A valid result would return:
question 1 answer 1 team A question 2 answer 2 team B question 4 answer 3 team D question 6 answer 3 team C question 7 answer 3 team F
I feel that it should be possible to accomplish this as a clean SQL statement with some clever use of Distinct and Take but I haven’t been able to get it right yet.
Best solution so far is from Mladen Prajdic. I have just updated it slightly to improve on it’s randomness:
SELECT TOP 10 * FROM (SELECT ROW_NUMBER() OVER(PARTITION BY Team ORDER BY Team, NEWID()) AS RN, * FROM Question ) teams WHERE RN = 2 ORDER BY NEWID()
for sql 2005 you can do this: