【问题标题】:query to extract random rows from a table从表中提取随机行的查询
【发布时间】:2015-04-23 03:13:54
【问题描述】:

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

【问题讨论】:

    标签: sql sql-server sql-server-2008 select stored-procedures


    【解决方案1】:

    您可以对问题进行随机排序(按分数),然后在 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
    

    【讨论】:

    • order by rand() 在 SQL Server 中不符合您的预期。 rand() 每次查询都会被评估一次,所以它的行为就像一个常量。在order by 表达式中,常数是不确定的(即您不知道结果会是什么),但它不是随机的。根据我的经验,它通常以“读取”顺序生成数据。
    • 就像@Gordon 说的!如果您修复查询,我将删除反对票。
    • @GordonLinoff 感谢您的评论 - 我不知道。改用newid(),IIUC 应该可以解决问题
    • @Andomar 将其替换为 newid(),这应该可以解决问题。
    【解决方案2】:
    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

    【讨论】:

      【解决方案3】:

      这就是想法。使用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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-04
        • 1970-01-01
        相关资源
        最近更新 更多