如何在Oracle SQL中将一个表中的行随机分配到另一个表中的行

时间:2019-02-25 05:19:40

标签: sql oracle plsql

我正在尝试找出一个SQL查询,该查询将把记录从一个表随机分配到另一个表。

例如: 我有一个客户表,我想从汽车表中为每辆汽车分配一个汽车。

我想确保这辆车是随机分配的,但是没有客户能够预测他们会收到哪辆车的财产。

客户: (乔恩,萨姆,萨拉,杰克,亚当,阿德里安)

汽车: (宝马,道奇,雷克萨斯)

结果:

(Jon-BMW,Sam-Lexus,Sara-BMW,Jack-Dodge,Adam-Dodge,Adrian-BMW)

如何在Oracle SQL中做到这一点?

3 个答案:

答案 0 :(得分:0)

这里是一个选择:

SQL> with t as
  2    (select u.name ||'-'||a.name comb,
  3       row_number() over (partition by u.name order by dbms_random.value(1, n.cnt)) rn
  4     from customers u cross join cars a
  5     join (select count(*) cnt from cars) n on 1 = 1
  6    )
  7  select t.comb
  8  from t
  9  where rn = 1;

COMB
-----------------------------------------
Adam-Lexus
Adrian-BMW
Jack-Lexus
Jon-BMW
Sam-Dodge
Sara-Lexus

6 rows selected.

SQL>

答案 1 :(得分:0)

一种可能比完全交叉联接更有效的方法是:

select c.*, cc.car
from (select c.*,
             row_number() over (order by dbms_random.value(1, cc.cnt) as seqnum
      from customers c cross join
           (select count(*) as cnt from cars) cc
     ) c join
     (select cc.*, row_number() over (order by dbms_random.random) as seqnum
      from cars cc
     ) cc
     on cc.seqnum = c.seqnum;

答案 2 :(得分:0)

如果不限制使用所有汽车和数据库资源:

select customer_name||'-'||car_name result 
from (
    select u.name customer_name, c.name car_name, 
        row_number() over ( partition by u.name order by dbms_random.value ) ord
    from customers u
    cross join cars c
)
where ord = 1