根据特定条件拆分SQL列

时间:2019-03-27 20:35:15

标签: sql sql-server substring charindex

我有一个如下表。

前景:

number

我正在尝试创建一个视图,该视图将把“约翰,富人和韦恩”这两个名字拉到一个名为“名字”的列中,然后在import Foundation // Function to determine whether a number is prime func isPrime(_ num: Int) -> Bool { let max = Int(floor(sqrt(Double(num)))) guard max >= 2 else { return true } for factor in 2...max { if num.isMultiple(of: factor) { // Write num % factor == 0 for older versions of Swift return false } } return true } // Find if a number is prime for numbers 2 to 200 for i in 2...100 { if isPrime(i) { print(i) } } 之后抓取这些名字并将它们放在一个名为

只有在有+----------------+---------------+----------------+ | Account NO | Contact | LastName | +----------------+---------------+----------------+ | 1233 | john bar | bar | | 2341324 | rich & mary johns | johns | | 21343 | wayne & elise smith| smith | +----------------+---------------+----------------+ 时才配偶。最后,我将创建一个姓氏列。

因此,配偶专栏应包含Mary和elise,并且对于John Bar是'&'

现在我正在使用以下内容,它可以提取名字和姓氏,没有问题。它还消除了“&”,但我在将“配偶”列中的配偶姓名与姓氏分开时遇到问题

'&'

我给配偶的返回值为'mary johns'和'elise smith'。我希望摆脱姓氏。

2 个答案:

答案 0 :(得分:0)

使用replace()和substring():

select 
  accountno AS [AccountNo],
  substring(contact, 1, charindex(' ', contact) - 1) AS [First],
  case 
    when contact like '% & %' then
      replace(
        replace(contact, ' ' + lastname, ''), 
        substring(contact, 1, charindex(' ', contact) + 2), '') 
    else ''
  end AS [Spouse],
  lastname AS [LastName]
from prospects

请参见demo
结果:

 AccountNo | First | Spouse | LastName
 --------: | :---- | :----- | :-------
      1233 | john  |        | bar     
   2341324 | rich  | mary   | johns   
     21343 | wayne | elise  | smith 

答案 1 :(得分:0)

您可以使用LEFTRIGHT提取名字和姓氏,并使用SUBSTRING获取可选的配偶姓名,如下所示:

SELECT  
    ACCOUNTNO,
    Contact,
    LEFT(Contact, CHARINDEX(' ', Contact) - 1) as First,
    CASE WHEN CHARINDEX(' & ', Contact) > 0
        THEN SUBSTRING(
            Contact, 
            CHARINDEX(' & ', Contact) + 3, 
            LEN(Contact) - CHARINDEX(' ', REVERSE(Contact)) - CHARINDEX(' ', Contact) - 2
        )
    END AS Spouse,
    RIGHT(Contact, CHARINDEX(' ', REVERSE(Contact)) - 1) AS Lastname
FROM Prospects

Demo on DB Fiddle

ACCOUNTNO | Contact             | First | Spouse | Lastname
--------: | :------------------ | :---- | :----- | :-------
     1233 | john bar            | john  | null   | bar     
    21343 | wayne & elise smith | wayne | elise  | smith   
  2341324 | rich & mary johns   | rich  | mary   | johns