PLSQL脚本,它在随机生成的表中的所有可能的数字对之间执行gcd

时间:2016-03-06 13:47:52

标签: oracle plsql

我必须创建一个包含10个条目的表,填充20-100的随机值。数字必须是不同的。然后我必须创建第二个表,填充所有可能的对(x,y)之间的最大公分母,其中x,y是第一个创建的表中的数字。这就是我到目前为止所做的:

                DROP TABLE random;
               CREATE TABLE random
                (
                 numbers int
                );

               DECLARE
               numberToInsert int;
                i int:=0;
               CURSOR c_random is select trunc(dbms_random.value(20,100)) from dual;
               BEGIN
               LOOP
               open c_random;
               i:=i+1;
               fetch c_random into numberToInsert;
               INSERT INTO random VALUES (numberToInsert);
               close c_random; 
               EXIT WHEN i = 10;
               END LOOP;
               END;
               /

因此,这将从20-100中随机插入10个不同的随机数。然而,这些数字并不总是截然不同。我不知道如何做第二部分。显然我需要使用while循环并执行Euclid算法。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

尝试此查询:

select x, y
from(
  select 19+level as x
  from dual
  connect by level <= 200-19
) cross join (
  select 19+level as y
  from dual
  connect by level <= 200-19
)
order by dbms_random.value()
fetch first 20 rows only;

查询生成两组从20到200的数字,然后使用cross jon组合这两组 - 这给出了一组不同的X,Y组来自两组 最后,查询使用&#34;随机排序&#34;然后挑选20个随机行 FIRST 20 ROWS ONLY子句适用于Oracle 12c,在早期版本中,您需要将此查询转换为子查询并使用WHERE rownum <= 20

要将结果插入表中,请使用simple:

INSERT INTO table ...
SELECT ....the above query....
  

查询的哪一部分确保数字不同?

嗯, CROSS JOIN 保证了这一点。

如果使用交叉联接合并两个不同集,则结果也将是不同。这是连接的工作方式 - 它将一个表中的所有行与另一个表中的所有行组合在一起 请看下面的简单示例,结果是distinc

select x, y
from(
  select 19+level as x
  from dual
  connect by level <= 22-19
) cross join (
  select 19+level as y
  from dual
  connect by level <= 22-19
)
        X          Y
---------- ----------
        20         20 
        20         21 
        20         22 
        21         20 
        21         21 
        21         22 
        22         20 
        22         21 
        22         22