繁体   English   中英

SQL Server:在第一列中获取最后4个字符,在第二列中获取单词的第一个字母,但忽略非字母

[英]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吗? 我试图从这两个现有的列IDDescription获取新列的新值。

  • 对于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)

在这里查看更多关于CONCAT功能的信息

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM