Search code examples
sqlsql-serverdatabasejoinouter-apply

How to join 2 tables without common key and randomly generate rows of second table


I have 2 tables.. [Users] and [Questions]

Users Table has..

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

And Question Table has..

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

Now, what I want is, select 5 random questions for each [User].

I've tried this query..

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

And it's resulting like to something like this..

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

The problem with this, the QuestId is being generated randomly but if you notice, each Users has the same generated random questions. I want each Users to have different set of random Questions.


Solution

  • Use this one:

    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