Postgresql 使用返回空的拆分部分将列拆分为列
我在postgres 9.6中有一列作为文本存储。这是一个地址,有些行的格式类似于BUILD NAME,40 我看到了答案,看起来就像我想要的,如果我跑的话Postgresql 使用返回空的拆分部分将列拆分为列,postgresql,split,Postgresql,Split,我在postgres 9.6中有一列作为文本存储。这是一个地址,有些行的格式类似于BUILD NAME,40 我看到了答案,看起来就像我想要的,如果我跑的话 select split_part('BUILD NAME, 40', ',', 2) as address_bldgno 它回来了;我要40 当我尝试时 select split_part(address, ', ', 1) as address_bldgname, split_part(address, ', ', 2) as ad
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;
它运行,但返回空值此处找到的答案;
应该是,
select somecol
,split_part(address, ', ', 1) as address_bldgname
,split_part(address, ', ', 2) as address_bldgno
from table;
通过向select中添加另一列,我将返回该列的所有值,并在存在拆分部分的地方生成拆分结果 如您所述:
…某些行具有格式
我怀疑任何不包含逗号的东西都会返回空值。
这是由于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和空字符串设置一些默认值,我建议您也阅读:很抱歉,但这并不能回答提出的问题。你的答案中所提供的解决方案与你尝试过的问题中所说的完全相同。你刚才用不同的语法重复了这一点:我选择了另一列somecol,结果与我预期的一样(即我从一个数字中得到了一个名称),在我对这个影响的回答中添加了解释。我不明白这里发生了什么,在你的示例中,你的结果就是我想要的结果。如果插入列名和表名,则不会得到任何结果。确实没有在查询中添加任何其他条件吗?可能与执行计划共享精确的表描述和精确的查询,因为我认为您遇到的问题不在拆分部分功能中。相关的后续回答和详细解释: