选择表示行的随机数

时间:2017-02-26 21:15:06

标签: sql oracle random plsql

我如何在PL / SQL中制作这个东西?

我想生成一个随机数,它将代表结果列表中的位置(行),该结果将按字段排序。

为了给出更详细的信息,假设我们有

ID:1,5,7,9,11,20,35

如何生成一个随机数,来自这些(1,5,7,9,11,20,35)?

4 个答案:

答案 0 :(得分:3)

 SELECT  id  from t  
 order by DBMS_RANDOM.VALUE  
 OFFSET 0  ROWS FETCH NEXT 1 ROWS ONLY

答案 1 :(得分:2)

这样的事情:

select id
from   ( select id, row_number() over (order by dbms_random.value()) as rn
         from   your_table
       )
where  rn = 1
;

在子查询中,为每行分配一个随机数,然后按这些随机数对行进行排序。在外部查询中,选择具有最低分配随机数的行。实际上,随机数被分配给每一行,但没有所有行的排序; Oracle优化器"了解"查询只是选择具有最小随机数的行,并且只进行实现该结果所需的工作。

答案 2 :(得分:1)

未经测试,但是像这样:

DECLARE
    new_array dbms_sql.varchar2_table;
BEGIN
    new_array(1) := 1;
    new_array(2) := 5;
    new_array(3) := 7;
    new_array(4) := 9;
    new_array(5) := 11;
    new_array(6) := 20;
    new_array(7) := 35;
    ar_count := new_array.count;
    rand_val := dbms_random.value(1,ar_count);
    dbms_output.put_line('Random from specific range '|| new_array(rand_val));

答案 3 :(得分:1)

您可以使用模数运算限制随机数的范围。然后,只需按照您的喜好排序值并使用ROWNUM,您就可以获得所选行的位置及其ID。 这是一个使用您提供的ID随机生成的数据集的代码。

WITH ds
     AS (SELECT 1 AS id,
                'tZdDNhGWzpAgYUA' AS val
         FROM   DUAL
         UNION
         SELECT 5 AS id,
                'yRuHolwoqySVhMTa' AS val
         FROM   DUAL
         UNION
         SELECT 7 AS id,
                'EZxaVsoQyIM' AS val
         FROM   DUAL
         UNION
         SELECT 9 AS id,
                'WLS' AS val
         FROM   DUAL
         UNION
         SELECT 11 AS id,
                'GJEatZb' AS val
         FROM   DUAL
         UNION
         SELECT 20 AS id,
                'SoQUTNLdbeXSnMxRnMw' AS val
         FROM   DUAL
         UNION
         SELECT 35 AS id,
                'GHTzCzkqQGZGGDtjcCzW' AS val
         FROM   DUAL),
     rand_id
     AS (SELECT MOD (ABS (DBMS_RANDOM.random ()), c)
                + 1
                   AS r_id
         FROM   (SELECT COUNT (*) AS c FROM ds))
SELECT b.rn AS position,
       b.id
FROM   rand_id a,
       (SELECT ROWNUM AS rn,
               id,
               val
        FROM   ds
        ORDER BY id) b
WHERE  a.r_id = b.rn;