how to select only particular value from Name - sql

i have a requirement to select only title from Name.
in the Name how to separate only title value and pass as title.
First_name Last_name Middle_Name Full_Name Title
NANCY HEINICK Null HEINICK,NANCY MD
CHARLES BONISKE H BONISKE,CHARLES H
THOMAS NEAL W NEAL,THOMAS W MD
In the above examples i need to select title and put it in title column if there is no title in full name i need is as NULL
Output
Title
MD
NULL
MD

Assuming the title is everything else, use replace() with a little extra logic:
select nullif(replace(replace(replace(replace(full_name, first_name, ''), last_name, ''), ',', ''), ' ', ''), '') as title
EDIT:
Because of the middle name (which I missed the first time around), it is better to concatenate all together and then replace:
select replace(full_name,
(last_name || ',' || first_name ||
coalesce(concat(' ', middle_name), '') || ' ',
), ''
) as title
Note that the code might vary slightly. Not all databases support the standard || operator for string concatenation.

You can try:
select ltrim(replace(full_name, (last_name + ',' + first_name + coalesce(' ' + middle_name, '')), ''))

Related

SQL to Take Last Name, First Name and MI and just return First and Last Name

I have searched Stack and getting close to what I need, but can't seem to figure out why when I have a person with just Last Name, First Name that the first name ends up as the Middle Initial? I am only needing the Last Name and First name to display it as First and Last name.
Sample Data:
EMP_ID
EMP_NAME
1234
JONES, JAMES R
5687
SMITH, BILL
What I want to end up with is:
EMP_ID
EMP_NAME_FULL
1234
JAMES JONES
5687
BILL SMITH
I am working with this code and once I can figure out how to resolve getting the first name to work, I planned to combine the First and Last Name substring/Parsing to one name.
SELECT DISTINCT
EMP_ID
,EMP_NAME
,SUBSTRING(EMP_NAME, 1, CHARINDEX(',', EMP_NAME) - 1) AS LASTNAME
,CASE WHEN PARSENAME(REPLACE(EMP_NAME, ',', '.'),1) LIKE '% %' THEN PARSENAME(REPLACE(PARSENAME(REPLACE(EMP_NAME, ',', '.'),1), ' ', '.'),2) ELSE PARSENAME(REPLACE(EMP_NAME, ',', '.'),1) END FIRSTNAME
,CASE WHEN PARSENAME(REPLACE(EMP_NAME, ' ', '.'),1) LIKE '%,%' THEN NULL ELSE PARSENAME(REPLACE(EMP_NAME, ' ', '.'),1) END MI
FROM EMP_TABLE
Try this:
[MYSQL]
select emp_name,
SUBSTRING_INDEX(SUBSTRING_INDEX(emp_name, ', ', -1), ' ', 1),
SUBSTRING_INDEX(emp_name, ',', 1)
from EMP_TABLE;
[MYSQL SSMS]
select emp_name,
CASE
WHEN CHARINDEX(' ', SUBSTRING(emp_name, CHARINDEX(', ',emp_name)+2)) >0
THEN SUBSTRING(SUBSTRING(SUBSTRING(emp_name, CHARINDEX(', ',emp_name)+2), ' '),1,CHARINDEX(' ',SUBSTRING(emp_name, CHARINDEX(', ',emp_name)+2)))
ELSE SUBSTRING(SUBSTRING(emp_name, CHARINDEX(', ',emp_name)+2), ' ')
END AS firstname,
SUBSTRING(emp_name, 1, CHARINDEX(',',emp_name) - 1) AS lastname
from EMP_TABLE;
I couldn't try it with MYSQL SSMS but the function CHARINDEX is the same as INSTR, the only difference is in INSTR you specify first where to look and then what to look.
I try it like this with your data and it worked.
Then, I convert every INSTR into CHARINDEX, and I inverted the parameters.
[DEMO]
with tmp as
(
select 'JONES, JAMES R' as emp_name from dual
union all
select 'SMITH, BILL' as emp_name from dual
)
select emp_name,
CASE
WHEN INSTR(SUBSTRING(emp_name, INSTR(emp_name,', ')+2),' ') >0
THEN SUBSTRING(SUBSTRING(SUBSTRING(emp_name, INSTR(emp_name,', ')+2), ' '),1,INSTR(SUBSTRING(emp_name, INSTR(emp_name,', ')+2),' '))
ELSE
SUBSTRING(SUBSTRING(emp_name, INSTR(emp_name,', ')+2), ' ')
END AS firstname,
SUBSTRING(emp_name, 1, INSTR(emp_name,',') - 1) AS lastname
from tmp;

Separate fullname into first and last, and remove 'junk'

Wasn't sure of the best way to word this. So I have a column with names, as below:
SalesPerson_Name
----------------
Undefined - 0
Sam Brett-sbrett
Kelly Roberts-kroberts
Michael Paramore-mparamore
Alivia Lawler-alawler
Ryan Hooker-rhooker
Heather Alford-halford
Cassandra Blegen-cblegen
JD Holland-jholland
Vendor Accounts-VENDOR
Other Accounts-OTHER
Getting the names separated is easy enough with PARSENAME and REPLACE functions, but where I'm running into a pickle is with getting rid of the 'junk' at the end:
SELECT SalesPerson_Key
,SalesPerson_Name
,CASE
WHEN PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 2) IS NULL
THEN PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 1)
ELSE PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 2)
END AS FirstName
,CASE
WHEN PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 2) IS NULL
THEN NULL
ELSE PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 1)
END AS LastName
FROM Salesperson
RESULTS FOR LASTNAME COLUMN:
LastName
--------
0
Brett-sbrett
Roberts-kroberts
Paramore-mparamore
Lawler-alawler
Hooker-rhooker
Alford-halford
Blegen-cblegen
Holland-jholland
Accounts-VENDOR
Accounts-OTHER
Specifically, I want to get rid of the text (userid) at the end of the last name. If the names were the same length, I could just use a RIGHT function, but they vary in length. Ideas?
select left(PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 1), len(SalesPerson_Name)-CHARINDEX('-',SalesPerson_Name)-1)
You are getting charindex of - and taking the left string of it.
If you just want to remove the last word (username) you can use a query like this
select
rtrim(
substring(
SalesPerson_Name,
1,
charindex('-',SalesPerson_Name,1)-1
)
)
from Salesperson
The charindex function locates the occurrence of the character/s you are looking for.
Consider whether hyphen is followed by a space or not, and split depending on these two cases
with Salesperson( SalesPerson_Name ) as
(
select 'Undefined - 0' union all
select 'Sam Brett-sbrett' union all
select 'Kelly Roberts-kroberts' union all
select 'Michael Paramore-mparamore' union all
select 'Alivia Lawler-alawler'
)
select case when substring(SalesPerson_Name,charindex(' ',SalesPerson_Name)+1,1) = '-' then
substring(SalesPerson_Name,charindex(' ',SalesPerson_Name)+3,len(SalesPerson_Name))
else
substring(SalesPerson_Name,charindex(' ',SalesPerson_Name)+1,len(SalesPerson_Name))
end as last_name
from Salesperson s;
last_name
------------------
0
Brett-sbrett
Roberts-kroberts
Paramore-mparamore
Lawler-alawler

Finding words with and without whitespaces in Rails and Postgresql

I'm trying to figure out a statement I can use in Ruby on Rails that does a SQL query to match a word that might or might not have any whitespaces with a similar word that also might or might not have any whitespaces.
For example:
Matthew Jones
or
MatthewJones
should match
Matthew Jones
or
MatthewJones
You can do this using postgres REPLACE function:
SELECT * FROM mytable
WHERE REPLACE(username, ' ', '') = REPLACE("Matthew Jones", ' ', '')
and it will match both MatthewJones and Matthew Jones.
You can write something like this in ActiveRecord query:
MyTable.where("REPLACE(username, ' ', '') = REPLACE('John Bob Jones', ' ', '')")
Update:
You can use ILIKE to make the query case-insensitive:
User.where("REPLACE(username, ' ', '') ILIKE REPLACE(?, ' ', '')", "John Bob Jones")
Thanks for that Rakibul. I've replaced the "=" with "ILIKE" so that it is also case-insensitive:
SELECT * FROM mytable
WHERE REPLACE(username, ' ', '') ILIKE REPLACE("Matthew Jones", ' ', '')
To do this using Active Record Query Interface in Ruby on Rails:
User.where("REPLACE(username, ' ', '') ILIKE REPLACE(?, ' ', '')", "Matthew Jones")

How To Use COALESCE() to Add Additional Characters

I have the following syntax on my SELECT Statement:
CONCAT(first_name, " ", COALESCE(middle_initial), " ", last_name) AS full_name
Obviously, what I get is the following:
For first_name='John' and middle_initial='A.' and last_name='Smith'
I get 'John A. Smith'
That is fine and is the desired result.
But I get an extra space for the following data (which I clearly understand why):
For first_name='John' and middle_initial='' and last_name='Smith'
I get 'John Smith'
Is there a way with COALESCE() to append " " if the condition returns a non-null value?
Thank you.
When middle_initial has '', you would want to:
SELECT CONCAT(first_name, ' ',
CASE
WHEN middle_initial is null OR middle_initial = '' then ''
ELSE CONCAT(middle_initial, ' ')
END
, last_name) AS full_name
SQLFiddle Example
COALESCE is used for checking NULL values, not handling empty strings, ''
select concat(first_name , ' ' ,
case when middle_initial is null then ''
when middle_initial = '' then ''
else concat(middle_initial, ' ') end ,
last_name)
this query asumes that first_name and last_name are not null nor empty string, in that case you can apply same logic to that fields
Try this
SELECT rtrim(Coalesce(first_name + ' ','')
+ Coalesce(nullif(middle_name,'') + ' ', '')
+ Coalesce(nullif(last_name,'') + ' ', ''))
FROM #table
SELECT rtrim(Coalesce('John' + ' ','')
+ Coalesce(nullif('A.','') + ' ', '')
+ Coalesce(nullif('Smith','') + ' ', ''))
SELECT rtrim(Coalesce('John' + ' ','')
+ Coalesce(nullif('','') + ' ', '')
+ Coalesce(nullif('Smith','') + ' ', ''))
I think best way is to do it like this. You can use such a constraction for any number of fields, variables and so on. Also it will correctly show you John or John A.
declare #Temp_Table table (first_name nvarchar(128), middle_initial nvarchar(128), last_name nvarchar(128))
insert into #Temp_Table
select 'John', null, 'Smith' union all
select 'John', 'A.', 'Smith' union all
select 'John', 'A.', null union all
select 'John', null, null
select
*,
stuff
(
isnull(' ' + nullif(first_name, ''), '') +
isnull(' ' + nullif(middle_initial, ''), '') +
isnull(' ' + nullif(last_name, ''), ''),
1, 1, ''
)
from #Temp_Table

Combining two column's data into one column in SQL?

I am trying to combine Last name, first name and middle name into single sort name column in a SQL statement. Sometime middle name will be NULL, and if that's the case, the sort name is showing NULL.
How to handle this?
SELECT TOP 500
Last_Name, First_Name, Middle_Name,
[Last_Name] + ',' + [First_Name] + ' ' + [Middle_Name] AS SORT_NAME
FROM [dbo].[usr_CUSTOMER]
ORDER BY SORT_NAME
Results:
Last_Name First_Name MiddleName Sort_Name
Aa Robert NULL NULL
But I want to see sort_name to be 'Aa,Robert'.
COALESCE:
COALESCE([Last_Name], '') + ',' + COALESCE([First_Name], '') + ' ' +
COALESCE(
[Middle_Name], '') AS SORT_NAME
Of course, this will leave ugly commas when last name or both first and middle are empty, so your actual code will need to be a bit more clever.
Use the ISNULL() function - it replaces a NULL value with something you define:
SELECT TOP 500
Last_Name, First_Name, Middle_Name,
[Last_Name] + ',' + [First_Name] + ' ' + ISNULL([Middle_Name], '') as SORT_NAME
FROM [dbo].[usr_CUSTOMER]
ORDER BY SORT_NAME
You can use the ISNULL function
ISNULL ( check_expression , replacement_value )
Docs : http://msdn.microsoft.com/en-us/library/ms184325.aspx
Note that I moved the space separating First and Middle name inside the COALESCE so that you avoid having a trailing space when Middle name is NULL.
..., [Last_Name]+ ','+ [First_Name] + COALESCE(' '+ [Middle_Name],'') as SORT_NAME...
Try
CONCAT(firstname,' ', LastName,' ', MiddleName) AS Full_Name