将姓氏与全名分开

时间:2012-12-14 13:43:39

标签: sql oracle

我想以这种格式显示我的数据:

First_Name  Mid_Name  Last_Name
All         Ahmad     Khan

这是我的代码

select substr(customer_name1, 0, instr(customer_name1, ' ')-1) as first_name
     , substr(customer_name1, instr(customer_name1, ' ')+1) as mid_name 
     , ... as last_name
  from sttm_customers 
 where customer_name1 = 'ALI AHMAD KHAN'

任何人都可以帮助我如何在报告中添加last_name吗?

5 个答案:

答案 0 :(得分:4)

你无法可靠地做到这一点,因为你没有可靠的方法来知道什么是名字,什么是姓氏。上面的例子显示了在空格上的拆分,但这并不能可靠地进行。

如果你有“John Fitzgerald Kennedy”,那就很容易了。你的名字是“John”,中间是“Fitzgerald”,最后是“Kennedy”。没问题。

如果你有“Mary Ann Summers”怎么办?名字应该是“Mary Ann”,姓氏是“Summers”,但是在空格上分裂并不知道。拆分空白会给你“玛丽”,“安”和“萨默斯”,这是错误的。

在相反的方向,如果你有“Eddie Van Halen”怎么办? “Eddie”是第一个名字,“Van Halen”是姓氏,但打破空白会给你“Eddie”,“Van”和“Halen”,这是错误的。

就此而言,你可以拥有“Mary Ann Van Halen”,然后你又做了什么?

底线:如果您没有将您的名字和姓氏捕获为单独的数据点,则无法将它们分开。

答案 1 :(得分:1)

SQL> select substr(customer_name1, 0, instr(customer_name1, ' ')-1) as first_name
  2       , substr(customer_name1, instr(customer_name1, ' ')+1,
  3                instr(customer_name1, ' ', -1, 1) - instr(customer_name1, ' ') - 1) as mid_name
  4       , substr(customer_name1, instr(customer_name1, ' ', -1) + 1) last_name
  5    from (select 'ALI AHMAD KHAN' customer_name1 from dual)
  6  /

FIR MID_N LAST
--- ----- ----
ALI AHMAD KHAN

这可以解决具有多个中间名的名称。

答案 2 :(得分:0)

这有点难看,但它会将每件作品分开:

with data(customer_name1) as
(
    select 'ALI AHMAD KHAN'
    from dual
),
first(firstname, customer_name1) as
(
    select substr(customer_name1, 0, instr(customer_name1, ' ')-1) as first_name,
        ltrim(replace(customer_name1, substr(customer_name1, 0, instr(customer_name1, ' ')-1), '')) customer_name1
    from data
),
middle(firstname, middlename, customer_name1) as
(
    select firstname, 
        substr(customer_name1, 0, instr(customer_name1, ' ')-1) middlename,
        ltrim(replace(customer_name1, substr(customer_name1, 0, instr(customer_name1, ' ')-1), '')) customer_name1
     from first
)
select firstname, middlename, customer_name1 as LastName
from middle

请参阅SQL Fiddle with Demo

答案 3 :(得分:0)

将-1作为起始位置,子字符串将从结束开始计数,然后

找到白色空间的instr希望它有所帮助

答案 4 :(得分:0)

从全名中分隔名字,中间名,姓氏。

它有效oracle 11g。考虑使用一个字段调用 uname 的表用户名,其中包含以下名称。

sachin ramesh tendulkar
shiva sudharson s
shiva kumar s
shiva nandhan s
shiva selvan s

要将名称拆分为查询下方的名字,中间名,姓氏。

select 
substr(uname,1, instr(uname,' ')) as firstname, 
substr(uname, instr(uname, ' '), instr(uname, ' ', 1, 2)-instr(uname, ' ')) as middlename,
substr(uname, instr(uname, ' ',1,2), length(uname)) as lastname from username;

结果如下:

sachin   ramesh  tendulkar
shiva    sudharson   s
shiva    kumar   s
shiva    nandhan     s
shiva    selvan  s