使用split_part将列拆分为列为空

时间:2017-07-21 20:36:20

标签: postgresql split

我在postgres 9.6中将列存储为text。这是一个地址,有些行的格式类似于BUILD NAME, 40

如果我跑的话,我看到this回答看起来像我想要的那样;

select split_part('BUILD NAME, 40', ',', 2) as address_bldgno

它返回;我想要40

当我尝试时;

select 
split_part(address, ', ', 1) as address_bldgname,
split_part(address, ', ', 2) as address_bldgno
from table;

它会运行但返回空值

2 个答案:

答案 0 :(得分:1)

如你所说:

  

......有些行有格式......

我怀疑任何不包含逗号的内容都会返回空值。 这是由于split_part条件找不到参数匹配。

为了说明在这里如何拆分不同的地址值,请参阅以下示例:

WITH    "table" ( address ) AS (
            VALUES
                ( 'BUILD NAME, 40' ),   -- first and second have value
                ( 'BUILD NAME' ),       -- only first have value (bldgname)
                ( '40' ),               -- only first have value (bldgname)
                ( ', 40' ),             -- first is empty string, second is value
                ( 'BUILD NAME,' ),      -- first is value, second is empty string
                ( NULL ),               -- both are NULL
                ( '' )                  -- no match found, both are empty strings
        )
SELECT  split_part( address, ', ', 1 ) as address_bldgname,
        split_part( address, ', ', 2 ) as address_bldgno
FROM    "table";


-- This is how it looks in result:
 address_bldgname | address_bldgno
------------------+----------------
 BUILD NAME       | 40
 BUILD NAME       |
 40               |
                  | 40
 BUILD NAME,      |
                  |
                  |
(7 rows)

如果你想为NULL和空字符串设置一些默认值,我建议你也阅读:this answer

答案 1 :(得分:0)

这里找到答案; PostgreSQL 9.3: Split one column into multiple

应该是;

select somecol 
,split_part(address, ', ', 1) as address_bldgname
,split_part(address, ', ', 2) as address_bldgno
from table;

通过向select中添加另一列,我将返回该列的所有值,并将split_part()结果存在。