查询从 table 中提取随机行

query to extract random rows from a table

我有以下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

我希望根据 table [Question_Format] 中设置的 [count] 从 table [问题] 中随机抽取问题。

 ID |     Question    
 ----------------------------
 2  |   How old are you?             
 3  |   Where are you from? 
 6  |   How was the training session?

这是想法。使用 row_number() 枚举每个 "mark" 的问题。然后用这个序号来select随机题:

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

您可以随机排序问题(按分数),然后在表 2 上进行非等式连接:

SELECT id, question
FROM   (SELECT id, question, marks, 
               ROW_NUMBER() OVER (PARTITION BY marks ORDER BY NEWID()) AS rn
        FROM   questions) q
JOIN   question_format qf ON q.marks = qf.mark AND q.rn <= qf.cnt