字段包含名字和姓氏。
PERSON:
Bob Franklin
Gene Smith
Roy G. Biv
我正在尝试创建一个查询,将姓氏放在第一位,然后是逗号,然后是第一个名字。那部分不是问题。我遇到的问题是Roy G. Biv。我没有回到他的姓氏,而是获得G. Biv。我写了一个单独的查询,正确返回姓氏,但我不知道如何将两者结合起来。
SELECT DISTINCT PERSON, SUBSTR(PERSON,INSTR(PERSON,' ')+1)|| ', '|| substr(person,1,INSTR(person,' ') -1) AS PERSONS
FROM LEDGER
返回:
Franklin, Bob
Smith, Gene
G. Biv, Roy
这个查询从中间名字的名称给出了我想要的结果:
select distinct person, SUBSTR(PERSON,INSTR(PERSON,'.')+1)
from ledger
where person like '%BIV'
返回:
Biv
将这些结合起来的最佳方法是什么?我是SQL的新手,对我很轻松!谢谢!
答案 0 :(得分:0)
您可以搜索向后计数的空间位置。查看INSTR here的文档:
SELECT DISTINCT PERSON, SUBSTR(PERSON,INSTR(PERSON,' ',-1,1)+1)|| ', '|| substr(person,1,INSTR(person,' ') -1) AS PERSONS
FROM LEDGER
来自文档的引用:
示例7-128使用字符位置向后搜索查找 子串的位置
在下一个示例中,函数从最后一个向后计数 字符到最后的第三个字符,这是第一个" o" 在" Floor"。然后该功能向后搜索第二个 发生"或",并发现第二次出现的开头 搜索字符串中的第二个字符。
SHOW INSTR('Corporate Floor','or', -3, 2) 2
答案 1 :(得分:0)
通常以空格分隔的名称,因此更容易使用substring_index:
SELECT
substring_index(PERSON, ' ', 1) AS first_name,
substring_index(PERSON, ' ',-1) AS last_name
FRON ledger
然后如果你想重新格式化为'last_name,first_name':
SELECT concat(
substring_index(PERSON, ' ',-1),
', ',
substring_index(PERSON, ' ', 1)
) AS full_name
FRON ledger
我使用first_name,last_name,有时是middle_name或other_names,一直在设计用户表。
我发现几乎所有时候都使用全名。因此,如果您大多数时候使用全名,那么一个字段实际上更好。
答案 2 :(得分:0)
onchange="filterCompanyList();"
答案 3 :(得分:0)
Oracle 解决方案
select regexp_replace (person,'(\S+)(\s+\S+)?\s+(\S+)','\3, \1') as persons
from ledger
+----------------+
| PERSONS |
+----------------+
| Franklin, Bob |
| Smith, Gene |
| Biv, Roy |
+----------------+
\s - A whitespace character.
\S - A non-whitespace character.
+ - Matches one or more occurrences
? - Matches zero or one occurrence
答案 4 :(得分:0)
substr(PERSON,INSTR(PERSON,' ', -1) )||', '|| substr(PERSON,1,INSTR(PERSON,' ', -1) )
答案 5 :(得分:0)
您可以直接使用下面提到的select语句。
select substr(PERSON,instr(PERSON,' ',-1))||', '||substr(PERSON,instr(PERSON,' ',1),instr(PERSON,' ',-1)-instr(PERSON,' ',1))||' '||substr(PERSON,0,instr(PERSON,' ',1)) from ledger;
或者用all子句将它全部带入,并从另一个看起来简单易用的select子句中调用它,如下所示:
with temp_ledger as (
select substr(PERSON,instr(PERSON,' ',-1)) as l_name ,substr(PERSON,instr(PERSON,' ',1),instr(PERSON,' ',-1)-instr(PERSON,' ',1)) as m_name, substr(PERSON,0,instr(PERSON,' ',1)) as f_name from ledger )
select l_name||', '||m_name||' '||f_name from temp_ledger;
注意:您还可以处理超过3个字的名称 “Jean Claude van Damme”