样本表
Child Parent
FF00001 12345
AA00002 12345
GG00003 12345
TT00003 12345
我想要的是这样的表
Parent FF AA GG TT
12345 FF00001 AA00002 GG00003 TT00003
前2个字母后面的数字可以是任何东西,但我知道它们总是AA,FF,GG,TT等。我可以转向类似的声明吗? like 'AA%'
答案 0 :(得分:2)
您可以使用这样的聚合:
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在子查询中查找前缀,然后在其上应用pivot。
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()
窗口函数,然后应用pivot:
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 - - -