基本上我需要获取邮政编码字符串中空格之前的部分。
我的当前查询是:
select postcode, left(postcode, length(postcode) - strpos(' ', postcode))
from postcodetable
但是它不能正确地返回邮政编码,例如:
第一列是NW1 1AA
,第二列应该只是NW1
,但实际上它只是重复了第一列。
基本上我需要获取邮政编码字符串中空格之前的部分。
我的当前查询是:
select postcode, left(postcode, length(postcode) - strpos(' ', postcode))
from postcodetable
但是它不能正确地返回邮政编码,例如:
第一列是NW1 1AA
,第二列应该只是NW1
,但实际上它只是重复了第一列。
您对 strpos()
的参数顺序是错误的。因此,您可以这样做:
select postcode, left(postcode, length(postcode) - strpos(postcode, ' '))
from (values ('NW1 1AA')) v(postcode);
你也可以使用带有正则表达式的 substring()
来完成这个操作:
select postcode, substring(postcode from '[^ ]+'::text)
strpos
函数中,参数顺序可能需要颠倒,而且 left
函数的第二个参数也是要从左边选取的字符数。因此正确的查询应该是:left(str text, n int)
返回字符串中前 n 个字符。当 n 为负数时,返回除了最后 |n| 个字符以外的所有字符。
select postcode, left(postcode, strpos(postcode, ' ')) from postcodetable