2017-02-23 64 views
1

樣品臺甲骨文轉動基於列的值的表使用像

Child Parent 
FF00001 12345 
AA00002 12345 
GG00003 12345 
TT00003 12345 

我想是這樣的

Parent FF  AA  GG  TT 
12345 FF00001 AA00002 GG00003 TT00003 

數字的前兩個字母后的表可以是任何東西,但我知道他們總是AA,FF,GG,TT等。我可以在一個類似的聲明中轉動嗎? like 'AA%'

回答

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找到一個子查詢前綴,然後將其應用於支點。

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 -  -  - 
+0

我喜歡聚合,但如果有重複?最大值將只顯示一行。示例FF0001和FF0002 – Jabda

+1

@Jabda - 請參閱更新。 – GurV

+0

令人驚歎!謝謝 – Jabda