Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query to extract random rows from a table

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?
like image 851
NITHIN SATHEESH Avatar asked Feb 21 '15 12:02

NITHIN SATHEESH


People also ask

How do I extract random rows in SQL?

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( ).

How do I SELECT a random row from a table in mysql?

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.

How do I SELECT a random row by group in SQL?

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();


2 Answers

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;
like image 66
Gordon Linoff Avatar answered Oct 16 '22 09:10

Gordon Linoff


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

like image 24
Roman Pekar Avatar answered Oct 16 '22 09:10

Roman Pekar