我试图通过MS执行以下SQL查询。 SQL, 目标是从两个查询中选择随机记录并将它们合并在一起,但它在ORDER BY NEWID()
生成错误当subject_id = 1
时,选择2个随机问题联合
当subject_id = 2
时,选择3个随机问题(SELECT TOP 2 REC_ID, REF_ID, SUBJECT_ID, QUESTIONS, ANSWERS
FROM dbo.questions WHERE (SUBJECT_ID= 1) ORDER BY NEWID() )
UNION ALL
(SELECT TOP 3 REC_ID, REF_ID, SUBJECT_ID, QUESTIONS, ANSWERS FROM
dbo.questions WHERE (SUBJECT_ID= 2) ORDER BY NEWID() )
答案 0 :(得分:1)
试试这个。
SELECT * FROM
(
SELECT TOP 2 REC_ID, REF_ID, SUBJECT_ID, QUESTIONS, ANSWERS
FROM dbo.questions
WHERE SUBJECT_ID= 1
ORDER BY NEWID()
) A
UNION ALL
SELECT * FROM
(
SELECT TOP 3 REC_ID, REF_ID, SUBJECT_ID, QUESTIONS, ANSWERS
FROM dbo.questions
WHERE SUBJECT_ID= 2
ORDER BY NEWID()
) B