1

我有 2 张桌子.. [用户] 和 [问题]

用户表有..

UserId Name
--     ----
1      Bob
2      Ang
3      Bill

问题表有..

QuestId Description CategoryId
------- ----------  --------
0       Question0   1
1       Question1   1
2       Question2   1
3       Question3   1
4       Question4   1
5       Question5   1
6       Question6   1
7       Question7   1
8       Question9   1
9       Question9   1
10      Question10  2

现在,我想要的是,为每个 [User] 选择 5 个随机问题。

我试过这个查询..

SELECT [User].UserId,Name, QuestId, Description from Users OUTER APPLY 
(SELECT TOP 5 QuestId, Description FROM Question WHERE CategoryId=1 ORDER BY NEWID(), 
Question.Id) RandomQuestions

结果就像这样..

UserId Name QuestId Description
------ ---- ------- -----------
1      Bob  2       Question2
1      Bob  3       Question3
1      Bob  6       Question6
1      Bob  8       Question8
1      Bob  9       Question9

2      Ang  2       Question2
2      Ang  3       Question3
2      Ang  6       Question6
2      Ang  8       Question8
2      Ang  9       Question9

3      Bill 2       Question2
3      Bill 3       Question3
3      Bill 6       Question6
3      Bill 8       Question8
3      Bill 9       Question9

问题在于,QuestId 是随机生成的,但如果您注意到,每个用户都有相同的随机生成问题。我希望每个用户都有不同的随机问题集。

4

2 回答 2

3

使用这个:

SELECT UserId,Name,QuestId, Description
FROM   Users  a
CROSS apply (
SELECT TOP 5 Row_number() OVER(ORDER BY (SELECT NULL)) AS RowNo, *
            FROM   (SELECT TOP 5 QuestId, Description
                    FROM   Question  b
                    WHERE  a.UserId = a.UserId 
                    ORDER  BY Newid()) S
) cs 
于 2020-01-08T04:27:11.323 回答
0

你需要QuestionID像这样随机

WHERE QuestId = (ABS(CHECKSUM(NEWID()) % 10)) + 1
于 2020-01-08T04:19:27.657 回答