随机将记录从一个表分配到另一个表

时间:2015-09-18 15:06:31

标签: sql teradata

我有两张桌子。

T1
id,date,item,channel

T2
id,date,item,channel

在T2中,id和date列为NULL。我想从T1中随机分配一个id和日期到T2中的每一行。此外,T2远小于T1。

任何想法如何做到这一点?我在Teradata 13上。

我原本想这样的事情:

sel count(*) from t2 ;
--507

select *
from (sel a.*, RANDOM(1,507) as r1 from t1) a
inner join (sel b.*, RANDOM(1,507) as r1 from t2) b
on a.r1 = b.r1

问题是我需要自动将t2的计数分配为随机的上限。

1 个答案:

答案 0 :(得分:1)

根据RANDOM排序分配ROW_NUMBER并加入:

select *
from
 (
   select dt.*, row_number() over (order by t1.r) as rn
   from
    ( 
      select t1.*, RANDOM(1,1000000) as r from t1
    ) as dt
 ) as a
join
 (
   select dt.*, row_number() over (order by t1.r) as rn
   from
    ( 
      select t2.*, RANDOM(1,1000000) as r from t2
    ) as dt
 ) as b   
  on a.rn = b.rn