如何将两个选择查询输出连接到一列

时间:2016-09-01 12:25:54

标签: sql oracle

我有这个问题:

SELECT s1 || s2 AS fullname, (
    SELECT SUBSTR('MarKJones',1,INSTR(translate('MarkJones', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXX' ),'X',2)-1) 
    FROM dual
) AS s1, (
    SELECT SUBSTR('MarkJones',INSTR(translate('MarkJones', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXX' ),'X',2)) 
    FROM dual
) AS s2,
FROM dual;

此查询无效。我需要将两个选择查询的输出组合为" Mark Jones"。请帮助解决这个问题。

提前致谢。

3 个答案:

答案 0 :(得分:0)

select s1 || ' ' || s2 as fullname, s1, s2
  from (
        select
               (select SUBSTR('MarkJones',1,INSTR(translate('MarkJones', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXX' ),'X',2)-1) from dual) as s1,
               (select SUBSTR('MarkJones',INSTR(translate('MarkJones', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXX' ),'X',2)) from dual) as s2
          from dual
       );

列别名不能用于同一请求,只能用于外部查询。

一般来说,您的问题已经解决了:

select regexp_replace('MarkJones','([A-Z])',' \1',2,1,'c') as fullname,
       regexp_substr('MarkJones','^[A-Z][a-z]+',1,1,'c') as s1,
       regexp_substr('MarkJones','[A-Z][a-z]+',2,1,'c') as s2
  from DUAL

答案 1 :(得分:0)

select s1 || ' ' || s2 as fullname, s1, s2
  from ( select SUBSTR('DebashisBhadra',1,
                INSTR(translate('DebashisBhadra', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                                      'XXXXXXXXXXXXXXXXXXXXXXXXXX' ),'X',2)-1) as s1,
                SUBSTR('DebashisBhadra',
                INSTR(translate('DebashisBhadra', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                                      'XXXXXXXXXXXXXXXXXXXXXXXXXX' ),'X',2))   as s2
          from dual
       );

FULLNAME        S1       S2   
--------------- -------- ------
Debashis Bhadra Debashis Bhadra

下面的变体可能效率较低,但可能更容易阅读,编写和维护。

with names ( str ) as ( select 'DebashisBhadra' from dual )
select s1 || ' ' || s2, s1, s2 
from (
      select substr(str, 1, regexp_instr(str, '[A-Z]', 2) - 1) as s1, 
             substr(str, regexp_instr(str, '[A-Z]', 2) )       as s2
        from names
);

答案 2 :(得分:0)

如果我理解正确,您的from位置错误:

SELECT s1.x || s2.x AS fullname
FROM (SELECT SUBSTR('DebashisBhadra', 1, INSTR(translate('DebashisBhadra', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXX' ), 'X' , 2)-1) as x
      FROM dual
     ) s1 CROSS JOIN
     (SELECT SUBSTR('DebashisBhadra', INSTR(translate('DebashisBhadra', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXX' ), 'X', 2)) as x
      FROM dual
     ) s2
FROM dual;

有更简单的方法来表达逻辑,但这似乎是您正在使用的方法的意图。