查询以从表中随机选择而不重复选择

时间:2018-12-27 23:13:57

标签: sql-server

我有两个表:[employee][task],我想将task的{​​{1}}表中的5个任务分配到一个跟踪表中。分配必须是随机的,每个选择都应排除已经选择的那些任务。

2 个答案:

答案 0 :(得分:0)

我想我已经找到一种实现您想要的目标的优雅方法。唯一的问题是,如果您的任务少于5 x员工,则某些员工将根本没有分配任何任务。

WITH    Employee    AS (SELECT ROW_NUMBER() OVER(ORDER BY NewID()) AS ID, * FROM Employee),
        Task        AS (SELECT ROW_NUMBER() OVER(ORDER BY NewID()) AS ID, * FROM Task)
    SELECT *  
    FROM Employee
    LEFT JOIN Task
        ON Employee.ID = FLOOR((Task.ID-1)/5)+1

您可以将所需结果插入“跟踪”表

根据您的评论,添加以确保任务按比例分配,如果任务> 5 x员工,则可能会发生问题,系统将为某些员工分配更多任务:

WITH    Employee    AS (SELECT ROW_NUMBER() OVER(ORDER BY NewID()) AS ID, * FROM Employee),
            Task        AS (SELECT ROW_NUMBER() OVER(ORDER BY NewID()) AS ID, * FROM Task)
        SELECT *  
        FROM Employee
        LEFT JOIN Task
            ON Employee.ID = FLOOR((Task.ID-1) %
                   (SELECT COUNT(*) FROM Employee)
                  )+1

它使用Modulus%运算符来获取其余的整数除法,因此,它为每个任务提供了相关数字,并且当雇员总数达到时,再次从1开始。

答案 1 :(得分:0)

在此帖子中:Return rows in random order由Robert Harvey在评论中链接,您可以找到有关执行涉及[oracle@~]$ sqlplus / as sysasm SQL*Plus: Release 12.2.0.1.0 Production on Fri Dec 28 20:31:40 2018 Copyright (c) 1982, 2016, Oracle. All rights reserved. Connected to: Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production SQL> startup pfile=/u02/app/grid/initASM.ora nomount ORA-01081: cannot start already-running ORACLE - shut it down first SQL> select name, state from v$asm_diskgroup; NAME STATE ------------------------------ ----------- REDO DISMOUNTED ARCHIVE DISMOUNTED DATA DISMOUNTED 甚至ORDER BY NewID()的查询效率低下的讨论。

根据我的经验,完成您要执行的操作的最佳方法是引入一个新的索引列,例如ORDER BY Rand(),用随机数(使用RandomColumn)填充一次,然后分别您希望随机的行选择一个随机数,例如Rand(),然后选择如下:

... R