您可以使用聚合這樣的:
select
parent,
max(case when child like 'FF%' then child end) FF,
max(case when child like 'AA%' then child end) AA,
max(case when child like 'GG%' then child end) GG,
max(case when child like 'TT%' then child end) TT
from your_table
group by parent;
其他的方法是使用SUBSTR找到一個子查詢前綴,然後將其應用於支點。
select *
from (
select
child,
parent,
substr(child, 1, 2) prefix
from your_table
)
pivot (
max(child) for prefix in ('FF' as FF,'AA' as AA,'GG' as GG,'TT' as TT)
)
兩個生產:
PARENT FF AA GG TT
---------------------------------------
12345 FF00001 AA00002 GG00003 TT00003
如果你有相同前綴的多個值,你想保持他們的所有,使用row_number()
窗函數在子查詢,然後應用透視:
with your_table (Child , Parent) as (
select 'FF00001', 12345 from dual union all
select 'FF00002', 12345 from dual union all
select 'AA00002', 12345 from dual union all
select 'GG00003', 12345 from dual union all
select 'TT00003', 12345 from dual
)
-- test data setup ends. See the solution below --
select parent, FF, AA, GG, TT
from (
select
child,
parent,
substr(child, 1, 2) prefix,
row_number() over (partition by parent, substr(child, 1, 2) order by child)
from your_table
)
pivot (
max(child) for prefix in ('FF' as FF,'AA' as AA,'GG' as GG,'TT' as TT)
)
產品編號:
PARENT FF AA GG TT
---------------------------------------
12345 FF00001 AA00002 GG00003 TT00003
12345 FF00002 - - -
我喜歡聚合,但如果有重複?最大值將只顯示一行。示例FF0001和FF0002 – Jabda
@Jabda - 請參閱更新。 – GurV
令人驚歎!謝謝 – Jabda