oracle sql 2列中的一列

时间:2018-12-11 03:26:21

标签: sql oracle oracle11g

我的数据库如下:

+-----+-----+
|FN   |LN   |
+-----+-----+
|FN1  |LN1  |
|FN2  |LN2  |
|FN3  |LN3  |
+-----+-----+

编辑: 我尝试过:

SELECT FN || ' - ' || LN Name FROM TBL;

输出:

+-----------+
|Name       |
+-----------+
|FN1 - LN1  |
|FN2 - LN2  |
|FN3 - LN3  |
+-----------+

但是我想要的是将它们加入同一列,但用新行隔开,如下所示:

+-----+
|Name |
+-----+
|FN1  |
|LN1  |
|FN2  |    
|LN2  |
|FN3  |
|LN3  |
+-----+

注意:FN和LN在同一行

3 个答案:

答案 0 :(得分:2)

您可以使用union all

select fn as name
from t
union all
select ln
from t;

如果您在乎订购:

select name
from (select fn as name, rownum as seqnum, 1 as ord
      from t
      union all
      select ln, rownum as seqnum, 2 as ord
      from t
     ) t
order by seqnum, ord;

请注意,子查询中没有order by,则不能保证两个子查询的结果将以相同的顺序进行。理想情况下,您需要一列来指定表中行的顺序。

答案 1 :(得分:1)

您可以使用LISTAGG来连接行,而使用CHR(10)来换行。

SELECT listagg(fn 
               ||chr(10) 
               ||ln, chr(10)) 
         within GROUP ( ORDER BY fn, ln) AS Name 
FROM   tbl;

Demo

答案 2 :(得分:1)

这将在输出中放置换行符-这也许就是您“注:FN和LN位于同一行”

select
     ( fn ||chr(10) || ln ) as name
from tbl

如果实际上确实需要更多行,尽管可以使用交叉联接来形成更多行,并使用case表达式从源列中选择性输出:

select
     case when n.n = 1 then tbl.fn else tbl.ln end as name
from tbl
cross join (select 1 n from dual union all select 2 from dual) n