如何在SQLite中获取名称首字母

时间:2018-01-10 21:50:54

标签: sql sqlite

SQLite是否有办法获取字符串中每个单词的第一个字母?例如:

姓名:

  

John Jonah Johnson

查询:

SELECT (get the initials from Name) as initials FROM Persons

结果:

  

JJJ

我找到了几个MySQL和SQL Server的例子,但到目前为止还没有找到SQLite。

编辑:

SQL Server的示例

SELECT SUBSTRING('Frank Thomas',1,1) + '.' +
SUBSTRING('Frank Thomas',CHARINDEX(' ','Frank Thomas')+1,1) + '.' AS Initials;

Initials
F.T.

MySQL的例子

mysql> SELECT CONCAT(SUBSTRING('Frank Thomas',1,1), '.', SUBSTRING('Frank Thomas
',LOCATE(' ','Frank Thomas')+1,1), '.') AS Initials;
+----------+
| Initials |
+----------+
| F.T.     |
+----------+

这些示例来自here

EDIT2:

目前,我做了以下内容:

 select (substr(Name,1,1) || '.' || 
 substr(Name,instr(Name,' ')+1,1) || '.' || 
 substr(substr(Name,instr(Name,' ')+1),instr(substr(Name,instr(Name,' ')+1),' ')+1,1) || '.')
 as Initials from Persons;

但即使名称中只有一个名称,这也会显示3个首字母。在SQLite中有更动态的方法吗?

1 个答案:

答案 0 :(得分:-1)

我有一个支持最多4个首字母的工作查询,但这很麻烦,有没有更简单,更动态的方法来做到这一点?

 select (substr(Name,1,1) || '.'
 || (case when (length(Name) - length(replace(Name, ' ', '')) + 1) > 1 then substr(Name,instr(Name,' ')+1,1) || '.'
 || (case when (length(Name) - length(replace(Name, ' ', '')) + 1) > 2 then substr(substr(Name,instr(Name,' ')+1),instr(substr(Name,instr(Name,' ')+1),' ')+1,1) || '.'
 || (case when (length(Name) - length(replace(Name, ' ', '')) + 1) > 3 then substr(substr(substr(Name,instr(Name,' ')+1),instr(substr(Name,instr(Name,' ')+1),' ')+1),(instr(substr(substr(Name,instr(Name,' ')+1),instr(substr(Name,instr(Name,' ')+1),' ')+1),' ')+1),1) || '.'
 else '' end) else '' end) else '' end)) as Initials from Persons;