[英]Snowflake - Extracting first & last name in a string
I have data where persons full name is one string.我有数据,其中人的全名是一个字符串。
There are 2 variations, one with comma (last name, first) and one with single space (First name, last)有 2 种变体,一种带有逗号(姓氏,名字),另一种带有单个空格(名字,姓氏)
John Smith约翰·史密斯
I was able to extract the last name using this:我能够使用以下方法提取姓氏:
,CASE WHEN POSITION(',',B.NAME,1) > 0 THEN SUBSTRING(B.NAME,0,POSITION(',',B.NAME,1)-1)
ELSE SUBSTRING(B.NAME,0,POSITION(' ',B.NAME,1)-1)
END AS LAST_NAME
Having trouble getting the first name though.虽然很难获得名字。 Any suggestions?
有什么建议么?
The split_part() function and iff() will do nicely here: split_part() function 和 iff() 在这里会做得很好:
-- Toggle between these options:
set nm = 'Smith, John';
set nm = 'John Smith';
select iff(POSITION(',' in $nm) > 0, split_part($nm, ',', 2), split_part($nm, ' ', 1)) FIRST_NAME
,iff(POSITION(',' in $nm) > 0, split_part($nm, ',', 1), split_part($nm, ' ', 2)) LAST_NAME
;
used what @JNevill suggested and did little modification.使用了@JNevill 的建议并且几乎没有修改。
with tab1 as
(
select 'Smith, John ' name
UNION select 'John Smith ' name
)
select CASE WHEN POSITION(',',B.NAME,1) > 0 THEN SUBSTRING(B.NAME,0,POSITION(' ',B.NAME,1)-2) ELSE STRTOK(B.Name, ' ', 2) END AS LastName,
CASE WHEN POSITION(',',B.NAME,1) > 0 THEN STRTOK(B.Name, ',', 2) ELSE STRTOK(B.Name, ' ', 1) END name
from tab1 B;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.