使用MS SQL对NEWID()和UNION进行排序

时间:2017-08-26 14:43:29

标签: sql-server union-all newid

我试图通过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() )

1 个答案:

答案 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