create table KeyList(
Key char(3),
Val char(2),
primary key (Key,Val));
insert into KeyList values('AAA','12');
insert into KeyList values('AAA','2A');
insert into KeyList values('AAA','32');
insert into KeyList values('AAA','44');
insert into KeyList values('BBB','11');
insert into KeyList values('BBB','33');
insert into KeyList values('BBB','8S');
commit;
col ConcatVal for a20
--■■■count関数で葉か判断1■■■
select Key,SubStr(sys_connect_by_path(Val,','),2) as ConcatVal
from (select Key,Val,
Row_Number() over(partition by Key order by Val) as Rank,
count(Key) over(partition by Key) as MaxLevel
from KeyList)
where Level = MaxLevel
start with Rank = 1
connect by Prior Key = Key
and Prior Rank = Rank-1
order by Key;
--■■■count関数で葉か判断2■■■
select Key,SubStr(sys_connect_by_path(Val,','),2) as ConcatVal
from (select Key,Val,
Lag(RowID) over(partition by Key order by Val) as LagRowID,
count(Key) over(partition by Key) as MaxLevel
from KeyList)
where Level = MaxLevel
start with LagRowID is null
connect by Prior RowID = LagRowID
order by Key;
--■■■Connect_by_IsLeafで葉か判断1(10g以降)■■■
select Key,SubStr(sys_connect_by_path(Val,','),2) as ConcatVal
from (select Key,Val,
Row_Number() over(partition by Key order by Val) as Rank
from KeyList)
where Connect_by_IsLeaf = 1
start with Rank = 1
connect by Prior Key = Key
and Prior Rank = Rank-1
order by Key;
--■■■Connect_by_IsLeafで葉か判断2(10g以降)■■■
select Key,SubStr(sys_connect_by_path(Val,','),2) as ConcatVal
from (select Key,Val,
Lag(RowID) over(partition by Key order by Val) as LagRowID
from KeyList)
where Connect_by_IsLeaf = 1
start with LagRowID is null
connect by Prior RowID = LagRowID
order by Key;
--■■■グループ化する方法■■■
select Key,max(SubStr(sys_connect_by_path(Val,','),2)) as ConcatVal
from (select Key,Val,
Lag(RowID) over(partition by Key order by Val) as LagRowID
from KeyList)
start with LagRowID is null
connect by Prior RowID = LagRowID
group by Key
order by Key;