在两个表之间随机分配记录

时间:2019-06-11 10:47:12

标签: sql oracle plsql

我想将表B中的值分配给表A,但要使表B中的每条记录出现相同的重复次数。

enter image description here

Fiddle SQL

3 个答案:

答案 0 :(得分:1)

您可以将窗口函数用于此和mod运算。为了简单的重复:

+----------+----+-------+
| date     | id | value |
+----------+----+-------+
| 1.3.2019 | 3  | 1     |
+----------+----+-------+

要获得更多随机分配,请随机化序列:

with a as (
      select a.*, rownum as seqnum
      from a
     ),
     b as (
      select b.*, rownum as seqnum, count(*) over () as cnt
      from b
     )
select a.col, b.col
from a join
     b
     on mod(a.seqnum - 1, b.cnt) = b.seqnum - 1;

答案 1 :(得分:0)

您可以使用ROWNUM实现相同的目的:

// decltype of a parenthesized variable is always a reference
decltype((i)) d; // error: d is int& and must be initialized
decltype(i) e;   // ok: e is an (uninitialized) int

Fiddler SQL QUERY

答案 2 :(得分:0)

尝试一下

with Employees as
 (select Emp, Row_Number() Over(order by 1) Rn
    from B
   cross join (select 1
                from Dual
              connect by level < (select count(1)
                                    from A) / (select count(1)
                                                          from B) + 1)
   order by Dbms_Random.Value),
Colours as
 (select Colour, Rownum Rn
    from A)
select t.Colour, k.Emp
  from Colours t
  join Employees k
    on t.Rn = k.Rn