unpivot查询连接到其他表

时间:2018-04-16 21:53:19

标签: sql oracle

我有一个如下的查询

with t as (
     select ID, name, tag, tag_1, tag_2, tag_3, tag_4, location from table_one
     )
     select * from t
     unpivot (
     value for _tag_ in (tag,tag_1,tag_2,tag_3,tag_4)
     )

现在,我想将其他3个表table1,table2,table3加入到上面,我需要从这些表中选择其他列示例col1,col2,col3。关于如何进行的任何想法。

1 个答案:

答案 0 :(得分:0)

我会在Oracle 12C +中使用横向连接:

select u.*
from t cross apply
     (select id, name, tag from dual union all
      select id, name, tag_1 from dual union all
      select id, name, tag_2 from dual union all
      select id, name, tag_3 from dual union all
      select id, name, tag_4 from dual
     ) u;

然后您可以像其他任何方式一样加入u

select u.*, . . . 
from t cross apply
     (select id, name, tag from dual union all
      select id, name, tag_1 from dual union all
      select id, name, tag_2 from dual union all
      select id, name, tag_3 from dual union all
      select id, name, tag_4 from dual
     ) u join
     x
     on u.? = x.?;

在Oracle 11中,如果将unpivot作为子查询或CTE,则可以执行类似的操作。