Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex string match in SQL Query

I have a complex scenario for string matching and want input from you guys. I have a table Named Customers. This table contains a field CustomerName varchar. Data in the column is prefixed with Mr. Mrs. Ms. Data could be

  1. Mr. John Brady
  2. Ms. Abraham Lenin
  3. Mrs. John Brady
  4. Mr. Michael King
  5. Mrs. Neil Thomas
  6. Mrs. Micheal King

Now I need to design a search query that returns me rows of only Couples and in a sequenced manner.

Like Select CustomerName from Customer where ...?? Result needs to be like

  1. Mr. John Brady
  2. Mrs. John Brady
  3. Mr. Michael King
  4. Mrs. Micheal King

Any Idea ?

Thanks in advance for the consideration.

like image 436
Asif Imam Avatar asked Sep 14 '26 02:09

Asif Imam


1 Answers

declare @T table(Name varchar(25))

insert into @T values
    ('Mr. John Brady'),
    ('Ms. Abraham Lenin'),
    ('Mrs. John Brady'),
    ('Mr. Michael King'),
    ('Mrs. Neil Thomas'),
    ('Mrs. Michael King')

;with C as
(
  select Name, 
         count(*) over(partition by stuff(Name, 1, charindex(' ', Name), '')) as Cnt
  from @T
)    
select Name
from C
where Cnt = 2
like image 68
Mikael Eriksson Avatar answered Sep 15 '26 19:09

Mikael Eriksson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!