SQL - Unable to find partially matching data in two columns - sql

I've never posted before, I've usually been able to find my answer, so please bear with me if I exclude anything or format incorrectly. Here is my issue:
I have two columns that include similar data, for example:
Column1 Column2
BASKETBALL BasketBall-CAVS
BASEBALL REDS Baseball-SPORTS
I am not searching for a specific word, just any word that is found in both columns should populate a "no" under a third column. So both of the above records should return a NO. I attempted this:
CASE
WHEN Column1 NOT LIKE
CONCAT('%',Column2,'%') THEN 'Yes'
ELSE 'No'
END AS Needs_Updated;
For some reason, only the first record pictured above returns a "No" in the "Needs_Updated" column. The second record returns a "Yes" (which isn't correct, two words match in that column). The only difference in the second record is there is multiple words in column 1. Can anyone help me out? Thanks in advance!

I think you can do what you want with regular expressions. Not all databases support them, so this is tricky with those databases.
Using MySQL syntax:
select t.*,
(case when column2 regexp replace(column1, ' ', '|') then 'no' else 'yes' end) as needs_updated
from t;

Have you tried Charindex
SELECT CASE WHEN CHARINDEX(Column2,Column1) > 0 ) THEN 'NO' ELSE 'YES' AS Needs_Updated
CHARINDEX ( expressionToFind , expressionToSearch [ , start_location ])
start_location is optional
https://learn.microsoft.com/en-us/sql/t-sql/functions/charindex-transact-sql

Related

Case sensitive for a specific column

I am using Microsoft SQL Management Studio V18. I have a column where I need to find if it contain any lower case alphabets. See below for desired output:
Material#
Material_Desc
Contain_Lower
123
PRODUCT DESCRIPTION
Yes
213
Product Description
No
Since the default collation is case insensitive I just want to turn it on for that specific column.
I've tried the following however it does not work - it does not identify if row2 contain a lower case alphabet. What can I do to identify if the column has a lower case?
select
table.Material_Desc,
Case when
table.Material_Desc collate SQL_Latin1_General_CP1_CS_AS = table.Material_Desc
Then 'No' else 'Yes' end as Contain_Lower
from table
You are on the right way, but you just forced the column to UPPER CASE. You also need to compare:
SELECT
material_desc,
CASE WHEN material_Desc = UPPER(material_desc) COLLATE SQL_Latin1_General_CP1_CS_AS
THEN 'No' ELSE 'Yes' END AS contain_lower
FROM table;

Return Condition/Expression from a Case Statement

I have searched all around and cannot seem to find a solution to this problem I'm having. I have a fairly large case statement (over 100 lines) that works and returns the result I am looking for. An example of the line is below:
case
When (Description like '%job%'
or description like '%job%fail%') then 'Job'
Else 'Not Classified'
End as ATC
I have a case statement that returns the result 'Job' as expected. I would also like to create a separate case statement that returns the criteria that returns the condition that the record met, allowing me to evaluate which criteria are returning the match ( a 'job' vs. 'job failed' comparison). I'm aware that I can duplicate my case statement to output the criteria met, but I would like to repeat this analysis and am looking for a more easily replicable solution (something along the lines of reading the conditions from the above case statement). Any thoughts?
If you're just trying to avoid repeating the logic you can wrap it up in a table expression.
with matches as (
select *,
case when Description like '%job%fail%' then 1 -- most specific first
when Description like '%job%' then 2 -- least specific last
else 0
end as MatchCode
from ...
)
select *,
case when MatchCode > 0 then 'Job' Else 'Not Classified' End as ATC
from matches

REPLACE not doing what I need in SQL

I've got a query pulling data from a table. In one particular field, there are several cases where it is a zero, but I need the four digit location number. Here is where I'm running into a problem. I've got
SELECT REPLACE(locationNbr, '0', '1035') AS LOCATION...
Two issues -
Whoever put the table together made all fields VARCHAR, hence the single quotes.
In the cases where there already is the number 1035, I get 1103535 as the location number because it's replacing the zero in the middle of 1035.
How do I select the locationNbr field and leave it alone if it's anything other than zero (as a VARCHAR), but if it is zero, change it to 1035? Is there a way to somehow use TO_NUMBER within the REPLACE?
SELECT CASE WHEN locationNbr='0' THEN '1035' ELSE locationNbr END AS LOCATION...
REPLACE( string, string_to_replace , replacement_string )
REPLACE looks for a string_to_replace inside a string and replaces it with a replacent_string. That is why you get the undesired behaviour - you are using the wrong function.
CASE WHEN condition THEN result1 ELSE result2 END
CASE checks a condition and if it is true it returns result1 and if it is not it will return result2. This is a simple example, you can write a case statement with more than one condition check.
Don't use replace(). Use case:
(case when locationNbr = '0' then '1035' else locationNbr end)
You can make use of length in Oracle:
select case when length(loacation) = 1 then REPLACE(loacation, '0', '1035') else loacation end as location
from location_test;

SQL computed column based on a special character on another column

I am not good with SQL at all, barely have an idea on how to do basic scripts suck as delete, drop, add.
I have this data with about 12 columns, I want to add a calculated column which will change depending if a special character shows up in another column.
lets say
A C
Money$ YES
Money NO
that is the idea, I want to create a column C where it says yes if there is a $ sign on the column A. Is this possible? I am assuming you can use something similar to an if condition but I have no experience with SQL scripting.
You would use a case expression and like:
select t.*,
(case when a like '%$%' then 'YES' else 'NO' end) as c
from t;
The following is just commentary.
This is very basic syntax for SQL. I would recommend that you spend some time to learn the basics. Learning-as-you-go is an okay approach -- assuming you have some fundamentals to build on. Otherwise, you are likely to spend a lot of time to learn a few things, and you may not learn the best way to do things.
yes, this is possible. you'll have to replace the parts in braces ({}) with the appropriate object names. I also use a bit rather than 'Yes'/'No'; as that seems better suited:
ALTER TABLE {YourTable} ADD {New Column Name} AS CONVERT(bit, CASE WHEN {Column} LIKE '%$%' THEN 1 ELSE 0 END) PERSISTED;
Note that this will return 0 if the column ({Column}) has a value of NULL, not NULL; unsure if this is the correct logic however, this should be more than enough to get the ball rolling. If not, read up on the CASE expression and NULL logic.
Regexp match can help you find out if there is a character you consider as special char in the strings:
SELECT
ColumnA
, SUBSTRING(ColumnA, PATINDEX('%[^ a-zA-Z0-9]%', ColumnA), 1) AS FirstSpecialChar
WHERE
ColumnA LIKE '%[^ a-zA-Z0-9]%'
;
The pattern [^ a-zA-Z0-9] will match on any character which is not a number, a space or an alphabetic character (note the ^ at the beginning of the character group - that mean NOT)
You can use regex to check any special character in column EX:
SQL SERVER
SELECT CASE WHEN 'ABCD$' Like '%[^a-zA-Z0-9]%' 1 THEN 'YES' ELSE 'NO' END as result
MYSQL
SELECT CASE WHEN 'ABCD$' REGEXP '[^a-zA-Z0-9]' = 1 THEN 'YES' ELSE 'NO' END as result
Regex can be changed as per the requirement
REGEXP '[^[:alnum:]]'

SQL CASE returning two values

I'm writing my first SQL CASE statement and I have done some research on them. Obviously the actual practice is going to be a little different than what I read because of context and things of that nature. I understand HOW they work. I am just having trouble forming mine correctly. Below is my draft of the SQL statement where I am trying to return two values (Either a code value from version A and it's title or a code value from version B and its title). I've been told that you can't return two values in one CASE statment, but I can't figure out how to rewrite this SQL statement to give me all the values that I need. Is there a way to use a CASE within a CASE (as in a CASE statement for each column)?
P.S. When pasting the code I removed the aliases just to make it more concise for the post
SELECT
CASE
WHEN codeVersion = A THEN ACode, Title
ELSE BCode, Title
END
FROM Code.CodeRef
WHERE ACode=#useCode OR BCode=#useCode
A case statement can only return one value. You can easily write what you want as:
SELECT (CASE WHEN codeVersion = 'A' THEN ACode
ELSE BCode
END) as Code, Title
FROM Code.CodeRef
WHERE #useCode in (ACode, BCode);
A case statement can only return a single column. In your scenario, that's all that is needed, as title is used in either outcome:
SELECT
CASE
WHEN codeVersion = "A" THEN ACode,
ELSE BCode
END as Code,
Title
FROM Code.CodeRef
WHERE ACode=#useCode OR BCode=#useCode
If you actually did need to apply the case logic to more than one column, then you'd need to repeat it.
Here is what I normally use:
SELECT
CASE
WHEN codeVersion = "A" THEN 'ACode'
WHEN codeVersion = "B" THEN 'BCode'
ELSE 'Invalid Version'
END as 'Version',
Title
FROM Code.CodeRef
WHERE
CASE
WHEN codeVersion = "A" THEN ACode
WHEN codeVersion = "B" THEN BCode
ELSE 'Invalid Version'
END = 'Acode'
my suggestion uses an alias. note on aliases: unfortunately you can't use the alias 'Version' in a where/group by clause. You have to use the whole case statement again. I believe you can only use an alias in an Order By.