生成随机数量的儿童记录

问题描述 投票:0回答:1

我成功地使用下面的代码来生成20条父母记录,每条记录有15条子女记录。我如何修改这段代码,为每个父记录生成一个随机数(即5-20)的随机子记录。

CREATE TABLE emp_info ( empid INTEGER, empname VARCHAR2(50) );

CREATE TABLE  emp_attendance    
(empid INTEGER,
 start_date DATE,
 end_date DATE
 );

-- 带CTE的选项

insert all 
  when rn = 1 then into emp_info   (empid, empname) values (id, name)
  when  1 = 1 then into emp_attendance (empid, start_date, end_date) 
               values (id, d1, d1 + dbms_random.value (0, .75))
with t as (select nvl(max(empid), 0)     maxid from emp_info)
select ceil(maxid + level/15) id,
       case mod(maxid + level, 15) when 1 then 1 end rn, 
       dbms_random.string('U',     dbms_random.value(3, 15)) name, 
       trunc(sysdate) +    dbms_random.value (1, 30) d1
  from t connect by level <= 20 * 15;
-- 20 parent records 15 children each
sql oracle parent-child
1个回答
1
投票

你可以利用 ROW_NUMBER 职能如下。

-- -- 解释见内联评论。

insert all 
  when rn = 1 then into emp_info   (empid, empname) values (id, name)
  when  1 = 1 then into emp_attendance (empid, start_date, end_date) 
               values (id, d1, d1 + dbms_random.value (0, .75))
select * from 
(
with t as (select nvl(max(empid), 0)     maxid from emp_info)
select ceil(maxid + level/15) id,
       case mod(maxid + level, 15) when 1 then 1 end rn, 
       dbms_random.string('U',     dbms_random.value(3, 15)) name, 
       trunc(sysdate) +    dbms_random.value (1, 30) d1,
       case when row_number() over (partition by ceil(maxid + level/15) 
                                        order by level) > 5 then 
       dbms_random.value(5, 20)
       else 5 end as random_val -- added this expression as column
  from t connect by level <= 20 * 20 -- changed it from 15 to 20
)
  where random_val <= 12; -- this is random number less than 20
© www.soinside.com 2019 - 2024. All rights reserved.