有两个表,我们称它们为PERSONS和PGROUP
create table persons(
id number(20),
name varchar2(30),
group_id number(30),
cnt number(2)
);
create table pgroup(
id number(20),
amount number(20));
insert into persons values(1,'name1',1,1);
insert into persons values(2,'name2',1,1 );
insert into persons values(3,'name3',1,1 );
insert into persons values(4,'name4',1,3 );
insert into persons values(5,'name5',null,5 );
insert into persons values(6,'name6',null,6 );
insert into persons values(7,'name7',null,7 );
insert into persons values(8,'name8',null,8 );
insert into persons values(9,'name9',null,9 );
insert into pgroup values(1,20000);
insert into pgroup values(2,12345);
表人员中的记录可能引用了pgroup(persons.group_id = pgroup.id
),但有时没有任何键。在这种情况下(persons.group_id is null
,该人“属于”每个组,因此我必须通过这两个组传播(“笛卡尔”)。
这样,我可以处理-一种选择以连接这些具有键的记录,并与笛卡尔合并。
但是我不知道如何基于列persons.cnt
复制它们。
F.E .:
人“ name9”的cnt = 9:
我需要将他的9张记录分成2组,
1组中的9条记录应具有amt = 20000
第2组中的另外9条记录应具有amt = 12345;
第一个问题-这种重复可以在SQL中完成吗? 2-我在这里描述的所有情况都可以在一个查询中完成(避免合并)吗?
答案 0 :(得分:0)
我认为以下查询正在完成任务:
-- Here is your sample data:
WITH persons (id, name, group_id, cnt) as
(select 1,'name1',1,1 from dual union all
select 2,'name2',1,1 from dual union all
select 3,'name3',1,1 from dual union all
select 4,'name4',1,3 from dual union all
select 5,'name5',null,5 from dual union all
select 6,'name6',null,6 from dual union all
select 7,'name7',null,7 from dual union all
select 8,'name8',null,8 from dual union all
select 9,'name9',null,9 from dual)
, pgroup (id,amount) as
(select 1,20000 from dual union all
select 2,12345 from dual)
-- As cnt is number(2) it's < 100, the following query get's all number between 1 and 99
, cnt as (select level cnt from dual connect by level < 100)
SELECT p.id
, p.name
, g.id group_id
, c.cnt
, g.amount
FROM persons p
JOIN cnt c
ON c.cnt <= p.cnt -- Get the duplicate records
join pgroup g
ON g.id = p.group_id
OR p.group_id is NULL -- Cartesian product if group_id is null
g.id
和c.cnt
列仅用于显示正确数量的重复项和笛卡尔乘积,您可能希望选择表persons
的相应值。