简体   繁体   English

从同一个表中选择多个列而不使用表联合

[英]Select multiple columns from the same table without tables union

I would like to create a query to select several columns from a table, and show the results as a single column. 我想创建一个查询以从表中选择多个列,并将结果显示为单个列。 I know I can do this with this query: 我知道我可以使用此查询执行此操作:

select a from Z
union
select b from Z
union 
select c from Z
union 
select d from Z
....

But in my case, table Z is a sub-query of about 50 lines, that I would not want to copy and paste. 但就我而言,表Z是一个大约50行的子查询,我不想复制和粘贴。 So I would like to have this in a query where Z appears only once. 所以我想在Z只出现一次的查询中有这个。 I don't know if this is possible. 我不知道这是否可行。

Do you know a way to do that? 你知道这样做的方法吗?

Thank you in advance. 先感谢您。

Regards. 问候。

From Oracle 11gR1 and up, you could use unpivot operator, ensure, of course that all columns are of the same datatype: 从Oracle 11gR1开始,您可以使用unpivot运算符,当然要确保所有列都具有相同的数据类型:

SQL> select val
  2    from (select 1 col1
  3               , 2 col2   
  4               , 3 col3
  5            from dual)
  6  unpivot(
  7    val for col in (col1, col2, col3)
  8  )
  9  ;

       VAL
----------
         1
         2
         3

You can do it using a WITH clause : 您可以使用WITH子句来完成它:

with Z as (
    select ... from ... -- <<== Put your big query here
)
select a from Z
union
select b from Z
union 
select c from Z
union 
select d from Z

The with clause at the top makes Z available to the remaining parts of your query without having to repeat yourself. 顶部的with子句使Z可用于查询的其余部分,而不必重复自己。

Here is a demo on sqlfiddle . 这是sqlfiddle上的一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM