如果c.forename
列为空或空白,我必须从c.known_as
获取姓氏。
当使用
CASE
WHEN IND.KNOWN_AS IS NULL OR ind.KNOWN_AS=''
THEN ind.FORENAMES
ELSE ind.KNOWN_AS
END AS 'Known As'
我的问题是在“姓氏”列中,我的名字像Jhon Smith,在这里我只想提取John,下面是我要实现的示例
Desire output c.forename
John Mr John
Jhon Jhon Smith
blank Jo
blank J
因此,基本上只需要跳过'Mr'即可使用姓氏,第二次只需要使用超过2个字符的姓氏即可。
我当前的查询是:
Select ind.FORENAMES,
ind.KNOWN_AS,
case when (known_as is null or known_as = '' ) and charindex(' ', forenames) > 2
then substring(forenames, 1, charindex(' ', forenames) - 1) end as FORENAMES2,
output
from individual ind
join member m on m.individual_ref=ind.individual_ref
and m.MEMBERSHIP_NO in ('001','002','003','004','005','006','007')
where m.member_status=33
答案 0 :(得分:1)
您可以使用以下case when
语句来验证您的条件:
对于SQL Server:
case when (c.known_as is null or c.known_as = '' )
and charindex(' ', c.forename) > 3 then substring(c.forename, 1, charindex(' ', c.forename) - 1) end
对于MySQL:
case when (c.known_as is null or c.known_as = '' )
and locate(' ', c.forename) > 3 then substring(c.forename, 1, locate(' ', c.forename) - 1) end
很少的解释:如果名字必须超过2个字符,则意味着名字空间必须至少出现在索引4处。而且条件是关于:locate(' ', c.forename) > 3
或substring(' ', c.forename) > 3
< / p>
注意
您必须首先在Mr
列中清除Mrs
,Ms
和c.forename
的所有出现,像这样(MySQL和SQL Server的语法):>
replace(replace(replace(c.forename, 'Mrs ', ''), 'Mr ', ''), 'Ms ', '')
您必须将其包含在查询中,例如:
Select FORENAMES,
KNOWN_AS,
case when (known_as is null or known_as = '' ) and charindex(' ', FORENAMES2) > 2
then substring(FORENAMES2, 1, charindex(' ', FORENAMES2) - 1) end as FORENAMES2,
output
from (
Select ind.FORENAMES,
ind.KNOWN_AS,
replace(replace(replace(ind.FORENAMES, 'Mrs ', ''), 'Mr ', ''), 'Ms ', '') FORENAMES2,
output
from individual ind
join member m on m.individual_ref = ind.individual_ref
where m.member_status=33
and m.MEMBERSHIP_NO in ('001','002','003','004','005','006','007')
)
答案 1 :(得分:0)
尝试一下:
DECLARE @DataSource TABLE
(
[name] VARCHAR(32)
);
INSERT INTO @DataSource ([name])
VALUES (' Mr John ')
,('Jhon Smith')
,(' Jo ')
,(' J ');
WITH SanitizeDataSoruce ([name], [name_reversed]) AS
(
SELECT LTRIM(RTRIM([name]))
,REVERSE(LTRIM(RTRIM([name])))
FROM @DataSource
)
SELECT [name]
,CASE
WHEN CHARINDEX(' ', [name]) > 1 THEN REVERSE(SUBSTRING([name_reversed], 0, CHARINDEX(' ', [name_reversed])))
ELSE ''
END
FROM SanitizeDataSoruce;