I have a table with multiple questions from different domains, example: Math, Physics, Chemistry and I have a query to select questions from that table and write them in a new table. What I have is selecting random questions from table with:
BEGIN
INSERT INTO tblTestDetailSSM (IdIntrebare, IdUserTest)
SELECT TOP 10 ti.IdIntrebare AS IdIntrebare, @IdUserTest
FROM (SELECT TOP 100 * FROM tblIntrebare ORDER BY NEWID()) ti JOIN tblProcedura tp ON ti.IdProcedura = tp.IdProcedura WHERE tp.Complexitate = 'GENERAL' AND tp.Specialitate = 'SSM';
END
where tp.Specialitate = 'SSM' includes all domains. I want to be able to select random questions, one from each domain and add it to tblTestDetailSSM. So that means multiple select query FROM which to select top 10. How do I do that?

Sarthak VarshneyPosted Jul 7, 2024, 9:00 AM
To select random questions from each domain and insert them into the
tblTestDetailSSMtable, you can use a combination of Common Table Expressions (CTEs) or derived tables to gather a random question from each domain first, and then perform the final insert operation.Here is an example of how you might achieve this:
Explanation:
RandomMathQuestions,RandomPhysicsQuestions,RandomChemistryQuestions, etc.) selects a random question from each specified domain usingORDER BY NEWID().UNION ALLoperation combines the results from all CTEs.#TempQuestionsto facilitate the final insert.tblTestDetailSSM.This approach ensures that you get one random question from each specified domain and insert them into the target table. If you need more questions per domain, adjust the
TOPclause accordingly.Siva VPosted Jul 7, 2024, 9:10 AM
As per your real time example random questions from different domains (Maths, physics, chemistry.. etc).
You can use CTE with Union all using Row_Number() window function in SQL.
Here RankedQuestions will
Hope this way of implementation will help you to solve your requirement.
Sarthak VarshneyPosted Jul 7, 2024, 9:05 AM
You're welcome!
Marius VasilePosted Jul 7, 2024, 9:03 AM
Thank you Sarthak, that was awesome solution!