使用两个不同的字符作为分隔符将列拆分为三列

时间:2014-08-12 21:26:21

标签: sql postgresql split pattern-matching

使用PostgreSQL,我想根据TWO(不是一个)字符拆分出现在我表中其中一列中的值。我的专栏id2包含以下值:

chr1:10000485-10006485@NM_022787@NMNAT1

我想将列拆分为三列(使用":"" - "字符作为分隔符:

chr1  |  10000485  | 10006485@NM_022787@NMNAT1

目前我的代码是:

select split_part(id2, ':', 1)s1,split_part(id2, ':', 2) s2, id2
from MyTable

输出如下(两列,其中s1和s2是标题):

s1    |     s2
chr1  |  10000485-10006485@NM_022787@NMNAT1

如何基于两者分割id2,":" AND" - "? 我能以某种方式使用s2进行顺序拆分吗?

我尝试使用:

select split_part(id2, ':', 1)s1,split_part(id2, ':', 2) s2, split_part(s2, '-', 2)

但收到了错误消息:

ERROR:  column "s2" does not exist
LINE 7: ... ':', 1)s1,split_part(id2, ':', 2) s2, split_part(s2, '-', 2...
                                                             ^
********** Error **********

ERROR: column "s2" does not exist
SQL state: 42703
Character: 160

2 个答案:

答案 0 :(得分:2)

您可以像这样使用'with'查询:

With q1 as (
   select split_part(id2, ':', 1) s1, split_part(id2, ':', 2) s2, id2
   from MyTable
   )
select s1, s2, split_part(s2, '-', 3) s3
from q1;

第一次接听电话。我稍后会纠正。

答案 1 :(得分:1)

一种方法是使用regexp_split_to_table()

SELECT regexp_split_to_table(id2, '[:-]')
FROM  (VALUES ('chr1:10000485-10006485@NM_022787@NMNAT1')) tbl(id2)

多行结果:

regexp_split_to_table
----------------------
chr1
10000485
10006485@NM_022787@NMNAT1

regexp_split_to_array()

SELECT regexp_split_to_array(id2, '[:-]')

然后您可以访问:

SELECT arr[1] AS s1, arr[2] AS s2, arr[3] AS s3 --, ...
FROM (
    SELECT regexp_split_to_array(id2, '[:-]') AS arr
    FROM  (VALUES ('chr1:10000485-10006485@NM_022787@NMNAT1')) tbl(id2)
    ) sub;

s1      s2          s3
--------------------------------------------
chr1    10000485    10006485@NM_022787@NMNAT1

或嵌套split_part() - 并按照评论中的要求将所有输入列添加到右侧:

SELECT split_part(id2, ':', 1) AS s1
      ,split_part(split_part(id2, ':', 2), '-', 1) AS s2
      ,split_part(split_part(id2, ':', 2), '-', 2) AS s3
      ,*
FROM  (VALUES ('chr1:10000485-10006485@NM_022787@NMNAT1')) tbl(id2);

相同的结果(加上所有输入列)。这实际上取决于你的琴弦如何变化。

解释错误

您得到的错误是因为您只能在SELECT列表中引用 input 列,而不是 output 列。
您需要将查询包装在子查询中以引用输出列(在您的情况下为s2),或者重复基于输入列的表达式,如演示上方。

相关问题