Finding words with and without whitespaces in Rails and Postgresql - sql

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")

Related

tsql - How do I parse a full name to pull out first name from these possible values

--How do I pull out first name using tsql from the possible values in a FullName field:
Here are possible values:
Richardson M.D., Asha R
Goines PHD, Jennifer
Goines P.H.D., Kevin G
Bourne M.D., T. David
From the below query, I am able to pull last name fine, but I am not able to get first name correctly. Is it possible with the type of data values?
select
SUBSTRING(pe2.full_name, 1, CHARINDEX(' ', pe2.full_name) - 1) AS "Rendering Provider: LastName",
SUBSTRING(pe2.full_name, CHARINDEX(', ', pe2.full_name) + 1, len(pe2.full_name)) AS "Rendering Provider: FirstName",
parsename(replace(pe2.full_name, ' ', ','), 3) as FirstName,
from personnel pe2
For the data posted in the question, and making no assumptions about other formats of data:
DROP TABLE #n;
CREATE TABLE #n (full_name nvarchar(100));
INSERT INTO #n (full_name)
VALUES ('Richardson M.D., Asha R'),
('Goines PHD, Jennifer'),
('Goines P.H.D., Kevin G'),
('Bourne M.D., T. David');
SELECT SUBSTRING(full_name,PATINDEX('%, %',full_name)+2,LEN(full_name)), full_name
FROM #n
parsename doesn't work that way, it returns values from a specified position in a "Dot" delimited string.
Example: I have a cat
select parsename(replace('I have a cat', ' ', '.'), 4) as FirstWord
select parsename(replace('I have a cat', ' ', '.'), 3) as SecondWord
select parsename(replace('I have a cat', ' ', '.'), 2) as ThirdWord
select parsename(replace('I have a cat', ' ', '.'), 1) as FourthWord
Try this instead to understand how it is parsing the firstname
parsename(replace(LTRIM(SUBSTRING(pe2.full_name, CHARINDEX(', ', pe2.full_name) + 1, len(pe2.full_name))), ' ', '.'), 2) AS FirstName
parsename(replace(LTRIM(SUBSTRING(pe2.full_name, CHARINDEX(', ', pe2.full_name) + 1, len(pe2.full_name))), ' ', '.'), 1) AS MiddleName
from personnel pe2

how to select only particular value from Name

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, '')), ''))

How can I CONCAT portions of three columns to one new column

I am trying to create a new column in my results that is made up on the first 3 characters of "PrimaryName", all of "VendorCity", and the first 5 characters of "VendorZip"
SELECT,VendorName
,replace(PrimaryVendorLocationName,' ','') as PrimaryName
,replace(PrimaryVendorLocationCity,' ','') as VendorCity
,replace(PrimaryVendorLocationZipCode,' ','') as VendorZip
FROM [table]
As you can see I also need to remove spaces to ensure a cleaner return. I would like to call the new column "NewVendorCode". So a record that originates like this:
R A Slack
Chicago Heights
60654-1234
Will return this:
RASChicagoHeights60654
You can use the following, using LEFT (MySQL / TSQL):
SELECT CONCAT(
LEFT(REPLACE(PrimaryVendorLocationName, ' ', ''), 3),
REPLACE(PrimaryVendorLocationCity, ' ', ''),
LEFT(REPLACE(PrimaryVendorLocationZipCode, ' ', ''), 5)
) FROM table_name
... or you can use SUBSTRING (MySQL / TSQL) (instead of LEFT):
SELECT CONCAT(
SUBSTRING(REPLACE(PrimaryVendorLocationName, ' ', ''), 1, 3),
REPLACE(PrimaryVendorLocationCity, ' ', ''),
SUBSTRING(REPLACE(PrimaryVendorLocationZipCode, ' ', ''), 1, 5)
) FROM table_name
Note: As you can see the SELECT querys work on MySQL and TSQL without change.
demo (MySQL): https://www.db-fiddle.com/f/wTuKzosFgkEuKXtruCTCxg/0
demo (TSQL): http://sqlfiddle.com/#!18/dbc98/1/1
You can use the following code:
SELECT VendorName+
replace(PrimaryVendorLocationName,' ','') +
replace(PrimaryVendorLocationCity,' ','') +
replace(PrimaryVendorLocationZipCode,' ','') as NewVendorCode
SELECT VendorName
,PrimaryName
,VendorCity
,VendorZip
,CONCAT(LEFT(PrimaryName,3),VendorCity,LEFT(VendorZip,5)) As NewVendorCode
FROM (
SELECT VendorName
,replace(PrimaryVendorLocationName,' ','') as PrimaryName
,replace(PrimaryVendorLocationCity,' ','') as VendorCity
,replace(PrimaryVendorLocationZipCode,' ','') as VendorZip
FROM [table]
)

Find value in comma-separated list

I have lists like this stored in a field in SQL:
Id MyListField
1 soy, meat, milk, wheat, nuts
2 soy, meat, nuts, milk, wheat
3 nuts
4 walnuts, nutshell, nuts
5 nuts, beans
6 walnuts, hazel nuts
7 nutshell, nutsize
This is not normalized and I can't change it. I now have to find nuts and replace them with insane (but keep e. g. hazel nuts and nutshell).
A Find is relatively easy, there are four cases and I have the placeholder character % at my disposal:
SELECT * FROM MyTable WHERE
MyListField LIKE 'nuts' OR
MyListField LIKE 'nuts, %' OR
MyListField LIKE '%, nuts' OR
MyListField LIKE '%, nuts, %'
But a Replace is hard, because I don't have placeholder or startofstring/endofstring characters:
UPDATE MyTable SET MyListField =
REPLACE(
REPLACE(
REPLACE(
REPLACE(
MyListField,
', nuts, ' ,
', insane, '
),
????,
????
),
????,
????
),
????,
????
)
WHERE
MyListField LIKE 'nuts' OR
MyListField LIKE 'nuts, %' OR
MyListField LIKE '%, nuts' OR
MyListField LIKE '%, nuts, %'
I can easily replace it in the middle of the string, but not at the start or the end. Or can I?
I am using SQL Server 2008, if that matters.
If you concatenate the field between , and _, then you only have one case to look for.
e.g.
update MyTable set MyFieldList = replace(', ' + MyFieldList + ',', ', nuts,', ', insane,')
update MyTable set MyFieldList = substring(MyFieldList, 3, len(MyFieldList) - 3)
By putting a comma at the start and end of the list, each element is wrapped in a leading ", " and a trailing ",".
Then your replace method becomes easy....
REPLACE(', ' + MyListField + ',',
', ' + #termToReplace + ',',
', ' + #replacement + ',')
Finally, strip the leading and trailing commas.
You could use something like
case
when Field = #val then #replaceVal
when Field like #val + ', %' then
#replaceVal + substring(Field, len(#val) + 1, len(Field))
when Field like '%, ' + #val then
left(Field, len(Field) - len(#val)) + #replaceVal
Just add all the remaining options, and you should be fine.
With all that help, it was easier than I thought it to be.
UPDATE MyTable
SET MyListField =
SUBSTRING(
REPLACE(
CONCAT(', ', MyListField, ', '),
', nuts, ',
', insane, '
),
3,
DATALENGTH(MyListField)+LEN('insane')-LEN('nuts')
)
WHERE CONCAT(', ',MyListField,', ') LIKE '%, nuts, %'
This works as long as there is one or zero occurrences in the string. If there can be more than one, it will fail, but this does not matter to me. If it matters to you, feel free to multiply the (LEN-LEN) part with How do you count the number of occurrences of a certain substring in a SQL varchar?

Concatenate and format text in SQL

I need to concatenate the City, State and Country columns into something like City, State, Country.
This is my code:
Select City + ', ' + State + ', ' + Country as outputText from Places
However, because City and State allow null (or empty) value, what happen is, (for example) if the City is null/empty, my output will look like , Iowa, USA; or say the State is empty, then the output will look like Seattle, , USA
Is there anyway I can format the output and remove "unnecessary" commas?
Edited: Because of the requirements, I should not use any other mean (such as PL/SQL, Store Procedure) etc., so it has to be plain SQL statement
select
isnull(City, '') +
case when isnull(City, '') != '' then ', ' else '' end +
isnull(State, '') +
case when isnull(State, '') != '' then ', ' else '' end +
isnull(Country, '') as outputText
from
Places
Since adding a string with null will result null so if they are null (not empty string) this will give you teh desired result
Select isnull(City + ', ','') + isnull(State + ', ' ,'') + isnull(Country,'') as outputText from Places
Use the COALESCE (Transact-SQL) function.
SELECT COALESCE(City + ', ', '') + COALESCE(State + ', ', '')...
In SQL Server 2012 you can use CONCAT function:
select concat(City,', ',State,', ',Country ) as outputText from Places
Not elegant by any means...
first changes city, state,country to null values if blank
then interprets that value for null and adds a space before a comma
then replaces any space comma space ( , ) with empty set.
Query:
SELECT replace(coalesce(Replace(City,'',Null),' ') + ', ' +
coalesce(Replace(State,'',Null), ' ' + ', ' +
coalesce(replace(Country,''Null),''), ' , ','') as outputText
FROM Places
Assumes no city state or country will contain space comma space.