如何将表中的col1,col2转换为row1和row2? col1是col2的父级

时间:2019-08-20 19:51:20

标签: sql

我的表格结构如下

seqno col1 col2 
1 Actuals apr19 
1 Actuals may19 
1 Actuals jun19 
2 budget apr19 
2 budget may19 
2 budget jun19

我需要以下格式的

     actuals                budget
apr19 may19 jun19       apr19 may19 jun19

1 个答案:

答案 0 :(得分:0)

您需要执行数据透视操作。每个RDBMS的操作语法略有不同。这是Oracle中的一个:

with t0 as (
 select 'Actuals' as c1, 'apr19' as c2 from dual
 union all select 'Actuals' as c1, 'may19' as c2 from dual
 union all select 'Actuals' as c1, 'jun19' as c2 from dual
 union all select 'budget' as c1, 'apr19' as c2 from dual
 union all select 'budget' as c1, 'may19' as c2 from dual
 union all select 'budget' as c1, 'jun19' as c2 from dual
)
select * 
from (
  select c1, c2
  from t0 
)
pivot (max(c2) 
       for c2 in ('apr19', 'may19', 'jun19'))
C1      | 'apr19' | 'may19' | 'jun19'
:------ | :------ | :------ | :------
Actuals | apr19   | may19   | jun19  
budget  | apr19   | may19   | jun19  

db <>提琴here