[英]SQL Server : to get last 4 character in first column and get the first letter of the words in 2nd column but ignore non alphabets
我可以检查是否可以以此要求运行SQL吗? 我试图从这两个现有的列ID
和Description
获取新列的新值。
ID
,只需检索最后4个字符 Description
,想获取每个单词的第一个字母,但忽略数字和符号。 要获取ID的后4个数字,您可以使用:
SELECT Id%10000 as New_Id from Tablename;
要获取每个单词的开头,您可以使用(答案为String2):
LEFT(Description,1)
这等效于使用SUBSTRING(Description,1,1)
这可以帮助您获取每个单词的第一个字母。
要将两者串联,可以使用CONCAT
函数:
SELECT CONCAT(String2,New_Id)
SQL Server具有糟糕的字符串处理功能。 即使split_string()
也不保留其找到的单词的顺序。
一种解决方法是使用递归CTE拆分字符串并累积首字母:
with t as (
select v.*
from (values (2004120, 'soccer field 2010'), (2004121, 'ruby field')) v(id, description)
),
cte as (
select id, description, convert(varchar(max), left(description, charindex(' ', description + ' '))) as word,
convert(varchar(max), stuff(description, 1, charindex(' ', description + ' ') , '')) as rest,
1 as lev,
(case when description like '[a-zA-Z]%' then convert(varchar(max), left(description, 1)) else '' end) as inits
from t
union all
select id, description, convert(varchar(max), left(rest, charindex(' ', rest + ' '))) as word,
convert(varchar(max), stuff(rest, 1, charindex(' ', rest + ' ') , '')) as rest,
lev + 1,
(case when rest like '[a-zA-Z]%' then convert(varchar(max), inits + left(rest, 1)) else inits end) as inits
from cte
where rest > ''
)
select id, description, inits + right(id, 4)
from (select cte.*, max(lev) over (partition by id) as max_lev
from cte
) cte
where lev = max_lev;
这是db <>小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.