需要有关在列中反转数据的帮助

时间:2011-07-18 20:15:23

标签: sql oracle

我有一个名为location的列,它包含数据:

texas_dallas florida_miami

我正在尝试创建一个SQL语句,它将摆脱_并颠倒顺序,以便我得到:

德克萨斯州达拉斯 迈阿密佛罗里达

到目前为止,我有这个声明似乎摆脱了下划线,只给了我_之前的条目。

SELECT SUBSTR(location,1,INSTR(location,'_') - 1)来自general的AS输出;

我在弄清楚我需要做的其他事情时遇到了一些麻烦。

3 个答案:

答案 0 :(得分:4)

编辑更正了输出顺序。

SQL> with general as (select 'texas_dallas' as location from dual
  2      union all select 'florida_miami' from dual)
  3  select substr(location, instr(location, '_') + 1)
  4      || ' ' || SUBSTR(location, 1 , INSTR(location, '_') -1) AS output
  5  from general;

OUTPUT
-------------------------------------------------------------------------------
dallas texas
miami florida

答案 1 :(得分:1)

您需要在表达式中添加更多内容。首先连接一个空格,然后使用SUBSTR函数提取紧跟在下划线之后的第二个单词。不向SUBSTR提供长度会使文本的其余部分结束。

select SUBSTR(location, 1 , INSTR(location, '_')-1 ) || ' ' || SUBSTR(location, INSTR(location, '_')+1 ) AS output 
from general ;

答案 2 :(得分:0)

您还可以尝试使用REGEXP_REPLACE函数:

select regexp_replace(location,'^(\S+)\_(\S+)$','\2 \1') from general;
相关问题