1

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

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'

谁能帮助我如何在报告中添加姓氏?

4

5 回答 5

4

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

如果你有“约翰·菲茨杰拉德·肯尼迪”,那很容易。你的名字是“约翰”,中间是“菲茨杰拉德”,最后是“肯尼迪”。没问题。

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

反之,如果你有“Eddie Van Halen”呢?“Eddie”是名字,“Van Halen”是姓氏,但是打破空格会给你“Eddie”、“Van”和“Halen”,这是错误的。

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

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

于 2012-12-14T14:19:26.873 回答
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

这可以处理具有多个中间名的名称。

于 2012-12-14T13:57:47.547 回答
0

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

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

于 2012-12-14T14:11:09.933 回答
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

于 2012-12-14T13:58:57.787 回答
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
于 2017-04-05T04:37:14.613 回答