从行到列的透视-Oracle SQL

时间:2019-04-30 11:15:39

标签: sql oracle pivot

我有一张桌子:

表1

row_id     var        var_val
1          Test 1      123
1          Test 2      456
1          Test 3      789
1          Test 4      1234
2          Test 1      665t
2          Test 2      dsfs
2          Test 3      df
2          Test 4      sfd
3          Test 1      sfs
3          Test 2      sf
3          Test 3      sdfs
3          Test 4      sfsd

以下是输出:

表2

row_id      var1        var2
1           123         456
2           665t        dsfs
3           sfs         sf
  • 对于var1-获取值,其中var =“ Test 1”
  • 对于var2-获取值,其中var =“ Test 2”

是否有一种方法可以使用数据透视表,或者是否可以按照上述方式从table1中为每个row_id提取变量?

3 个答案:

答案 0 :(得分:1)

您可以使用条件聚合或join

select t11.row_id, t11.var, t12.var
from table1 t11 join
     table1 t12
     on t11.row_id = t12.row_id and
        t11.var = 'Test 1' and
        t12.var = 'Test 2'

答案 1 :(得分:0)

  

是否可以使用数据透视...?

确定:

select * 
  from table1
  pivot (max(var_val) for var in ('Test 1' var1, 'Test 2' var2))

demo

答案 2 :(得分:0)

您可以同时使用correlated subqueriesrow_number()窗口分析功能

with table1(row_id, var, var_val) as
(
 select 1,'Test 1','123'  from dual union all
 select 1,'Test 2','456'  from dual union all
 select 1,'Test 3','789'  from dual union all
 select 1,'Test 4','1234' from dual union all
 select 2,'Test 1','665t' from dual union all
 select 2,'Test 2','dsfs' from dual union all
 select 2,'Test 3','df'   from dual union all
 select 2,'Test 4','sfd'  from dual union all
 select 3,'Test 1','sfs'  from dual union all
 select 3,'Test 2','sf'   from dual union all
 select 3,'Test 3','sdfs' from dual union all
 select 3,'Test 4','sfsd' from dual
), t2 as
(
select t.*, row_number() over (partition by var order by row_id) as rn
  from table1 t
)
select distinct row_id,
                (select var_val
                   from table1 t2
                  where t2.var = 'Test 1'
                    and t2.row_id = rn) as var1,
                (select var_val
                   from table1 t2
                  where t2.var = 'Test 2'
                    and t2.row_id = rn) as var2
  from t2
 order by row_id

 ROW_ID VAR1    VAR2
 ------ ----    ----
 1      123     456
 2      665t    dsfs
 3      sfs     sf

Demo