Oracle PL / SQL循环通过未定义数量的组

时间:2016-09-09 11:54:57

标签: oracle plsql logic

我正在为下面的数据集编写一个oracle PL / SQL过程。

Column1---Column 2---Column 3
ID-1      Group1     Item 11
ID-1      Group1     Item 12
ID-1      Group1     Item 13
ID-1      Group2     Item 21
ID-1      Group2     Item 22
ID-2      Group3     Item 31
ID-2      Group3     Item 32
ID-2      Group4     Item 41
ID-2      Group5     Item 51
ID-2      Group5     Item 52

根据输入ID,我会得到几个组,每个组中的项目很少。我需要一个连接如下的结果集:

输入:ID-1 单列OutPut:

Item 11 - Item 21
Item 11 - Item 22
Item 12 - Item 21
Item 12 - Item 22
Item 13 - Item 21
Item 13 - Item 22

输入:ID-2 单列OutPut:

Item 31 - Item 41 - Item 51
Item 31 - Item 41 - Item 52
Item 32 - Item 41 - Item 51
Item 32 - Item 41 - Item 52

输出应包含属于输入ID的每个组中一个项目的所有组合。 请注意,ID下的数字组不固定,组中的项目数不固定。

2 个答案:

答案 0 :(得分:1)

使用dense_rank()对您的组进行编号,然后使用此列在分层查询中的connect by子句中进行通信:

select ltrim(sys_connect_by_path(column3, ' - '), ' - ') as list 
  from (select dense_rank() over (order by column2) rnk, column1, column2, column3
          from yourtable where column1 = 'ID-1')   
  where connect_by_isleaf = 1
  connect by prior rnk + 1 = rnk 
  start with rnk = 1

测试数据和输出:

create table yourtable (Column1 varchar2(10), Column2 varchar2(10), Column3 varchar2(10));
insert into yourtable values( 'ID-1', 'Group1', 'Item 11');
insert into yourtable values( 'ID-1', 'Group1', 'Item 12');
insert into yourtable values( 'ID-1', 'Group1', 'Item 13');
insert into yourtable values( 'ID-1', 'Group2', 'Item 21');
insert into yourtable values( 'ID-1', 'Group2', 'Item 22');
insert into yourtable values( 'ID-2', 'Group3', 'Item 31');
insert into yourtable values( 'ID-2', 'Group3', 'Item 32');
insert into yourtable values( 'ID-2', 'Group4', 'Item 41');
insert into yourtable values( 'ID-2', 'Group5', 'Item 51');
insert into yourtable values( 'ID-2', 'Group5', 'Item 52');

LIST
--------------------
Item 11 - Item 21
Item 11 - Item 22
Item 12 - Item 21
Item 12 - Item 22
Item 13 - Item 21
Item 13 - Item 22    

答案 1 :(得分:0)

select substr(B.perm,4,length(B.perm)) from 
(select level l,sys_connect_by_path(A.Column3, ' - ') as perm , sys_connect_by_path(A.Column2, ' - ') ttt
from (select t.* from yourTable t where t.Column1 = 'ID-2')A -- ID-2 is your input
connect by level <= 3 -- 3 is your distinct group count for your input
order by level)B
where B.l = 3 and instr(B.ttt , 'Group3 - Group4 - Group5') > 0 -- 3 is your distinct group count for your input , *** Group3 - Group4 - Group5 is your merged data according to your input
order by substr(B.perm,4,length(B.perm))asc

我测试它,如果你设置正确的值,它可以同时使用两个ID。