我有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
现在,我要为每个[用户]选择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是随机生成的,但是如果您注意到,每个用户都有相同的生成随机问题。我希望每个用户都有不同的随机问题集。
答案 0 :(得分: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
答案 1 :(得分:0)
您需要像这样随机QuestionID
WHERE QuestId = (ABS(CHECKSUM(NEWID()) % 10)) + 1