尝试类似:
with x as (
select 1 as person_id, 'JOE BLOW' as fullname from dual
union all
select 1 as person_id, 'JOE SNOW' as fullname from dual
union all
select 2 as person_id, 'JANE DOE' as fullname from dual
)
select *
from
(
select person_id, fullname, row_number() over (partition by person_id order by fullname) rnum
from x
)
pivot (
max(fullname)
-- allow up to 5 names per person
for rnum in (1 name1,2 name2,3 name3,4 name4,5 name5)
);
输出:
PERSON_ID NAME1 NAME2 NAME3 NAME4 NAME5
1 JOE BLOW JOE SNOW
2 JANE DOE
编辑:
如果您想要基于附加 STATUS 字段的单独行,每个人每个状态最多 5 个名称,那么您将拥有:
with x as (
select 1 as person_id, 'JOE BLOW' as fullname, 'Active' as status from dual
union all
select 1 as person_id, 'JOE SNOW' as fullname, 'Inactive' as status from dual
union all
select 1 as person_id, 'JOE ROGAN' as fullname, 'Inactive' as status from dual
union all
select 2 as person_id, 'JANE DOE' as fullname, 'Active' as status from dual
)
select *
from
(
select person_id, fullname, status, row_number() over (partition by person_id, status order by fullname) rnum
from x
)
pivot (
max(fullname)
-- allow up to 5 names per person
for rnum in (1 name1,2 name2,3 name3,4 name4,5 name5)
);
输出:
PERSON_ID STATUS NAME1 NAME2 NAME3 NAME4 NAME5
1 Active JOE BLOW
1 Inactive JOE ROGAN JOE SNOW
2 Active JANE DOE
所以 person_id=1 有 1 个活跃的名字和 2 个不活跃的名字。