我有以下2个表
表1 - 问题
包含为每个问题分配的问题和标记
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
表2 - 问题格式
包含要为一组标记提取的问题(计数)的数量
Mark | Count
-------------
2 | 2
5 | 1
我想根据表[Question_Format]中设置的[count]从表[Questions]中选择随机问题。
ID | Question
----------------------------
2 | How old are you?
3 | Where are you from?
6 | How was the training session?
答案 0 :(得分:5)
这是个主意。使用row_number()
枚举每个“标记”的问题。然后使用此序号来选择随机问题:
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;
答案 1 :(得分:5)
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 :(得分:5)
你可以随机排序问题(每个标记),然后在table2上有一个不相等的连接:
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