I have the following 2 tables
Table 1 - Questions
Contains questions and marks allotted for each questions
ID| Questions | Marks
________________________________________
1 | What is your name? | 2
2 | How old are you? | 2
3 | Where are you from? | 2
4 | What is your father's name? | 2
5 | Explain about your project? | 5
6 | How was the training session?| 5
Table 2 - Question Format
Contains how many questions (count) to be extracted for a set of Marks
Mark | Count
-------------
2 | 2
5 | 1
I want the random questions to be picked up from the table [Questions] as per the [count] set in the table [Question_Format].
ID | Question
----------------------------
2 | How old are you?
3 | Where are you from?
6 | How was the training session?
To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly. It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).
First, we have specified the table name to which we are going to select random records. Second, we have specified the RAND function that returns random values for each row in the table. Third, we have specified an ORDER BY This clause sorts all table rows by the random number generated by the RAND() function.
Now let's find how to do Random Sampling within Groups in SQL using RAND() function. Below SQL statement is to display rows in random order using RAND() function: Query: SELECT * FROM table_name order by RANDOM();
Here is the idea. Enumerate the questions for each "mark" by using row_number()
. Then use this sequential number to select the random questions:
select q.*
from (select q.*,
row_number() over (partition by marks order by newid()) as seqnum
from questions q
) q join
marks m
on q.marks = m.mark and q.seqnum <= m.count;
with cte as (
select *, row_number() over(partition by Marks order by newid()) as rn
from Questions
)
select
q.id, q.Questions
from cte as q
inner join QuestionFormat as qf on qf.Mark = q.Marks
where q.rn <= qf.[Count]
sql fiddle demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With