I need a sql query that will randomly pick 20 records from a table that contains about 100 records. Each record has an associated category that goes from 1 to 15. I want the records that are picked to be completely random. However, I can't have 3 records from the same category being picked.
It seems to me that I can randomly pick 20 records and then eliminate records which contain a given category >=3 times. And then pick again. But all these implies having more than one query. And I don't know how to pass the results of one query to another and then another in microsoft access query. The query results are supposed to serve as a control source for a form. What do i do so that just one query will give me the results which can then be used as a control source for the form?
I tried the following and the problem is that the questions from the same category are grouped together which is not what I want. Here's a sample of what I am trying.
`(SELECT TOP 3 MCQuestionsT.QuestionID, MCQuestionsT.QuestionText, MCQuestionsT.CategoryID
FROM MCQuestionsT
WHERE (((MCQuestionsT.CourseCode)="2323") AND MCQuestionsT.CategoryID = 1)
ORDER BY Rnd(MCQuestionsT.QuestionID))
UNION ALL
(SELECT TOP 3 MCQuestionsT.QuestionID, MCQuestionsT.QuestionText, MCQuestionsT.CategoryID
FROM MCQuestionsT
WHERE (((MCQuestionsT.CourseCode)="2323") AND MCQuestionsT.CategoryID = 2)
ORDER BY Rnd(MCQuestionsT.QuestionID))
UNION ALL
(SELECT TOP 3 MCQuestionsT.QuestionID, MCQuestionsT.QuestionText, MCQuestionsT.CategoryID
FROM MCQuestionsT
WHERE (((MCQuestionsT.CourseCode)="2323") AND MCQuestionsT.CategoryID = 3)
ORDER BY Rnd(MCQuestionsT.QuestionID))
`
-- example using sys.all_objects that returns three random objects of each type
SELECT type_desc, name
FROM (
SELECT type_desc, name, Id = ROW_NUMBER() OVER (PARTITION BY type_desc ORDER BY NEWID())
FROM sys.all_objects
) Q
WHERE Id < 4
-- example using your table
SELECT QuestionID, QuestionText, CategoryID
FROM (
SELECT QuestionID, QuestionText, CategoryID, Id = ROW_NUMBER() OVER (PARTITION BY CategoryID ORDER BY NEWID())
FROM dbo.MCQuestionsT
WHERE CourseCode = '2323'
) Q
WHERE Id < 4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.