How can I compare two string values in SQL? - sql

The problem statement is as mentioned below:
When max_pos> 4 and max_neg is >1
then find out the name of rollercoaster
where intensity_level is greater than excitement_level.
Here, the intensity_level and excitement_level are string values like high, very high etc. How can I compare them?

You could use CASE expression to map value for your intensity_level and excitement_level, then compare them
SELECT *
FROM table_name
WHERE
max_pos> 4
AND max_neg >1
AND
(
CASE
WHEN intensity_level = 'high' THEN 0
WHEN intensity_level = 'very high' THEN 1
WHEN intensity_level = 'ultra high' THEN 2
END
>
CASE
WHEN excitement_level = 'high' THEN 0
WHEN excitement_level = 'very high' THEN 1
WHEN excitement_level = 'ultra high' THEN 2
END
);

You can create a table that contains intensity_level and excitement_level for each rollercoaster as integers and an ID that links them to your main table

try using DECODE. DECODE high, very high values with a number and alias and then select all from this result set, then compare the aliases

Here My solution using the function
Just assign a integer value to the string and then compare the integer value.
CREATE function Weight(tag VARCHAR(200))
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE v INT;
IF tag='High' THEN
SET v=1;
END IF;
IF tag='Very High' THEN
SET v=2;
END IF;
RETURN v;
END;|
Then use the query
Select *
From tablename
Where max_pos> 4
AND max_neg is >1
AND Weight(intensity_level)>Weight(excitement_level);
The Weight function above maybe not work in SQL, I used MySQL so change accordingly.

Related

SQL query to get a result divided by 2

Given a table with column like city and cityId,Adderesses. How would i write a query that gives a list cities where cityID is only even numbers. Plz explain in details.
Use the modulo operator
select * from your_table
where mod(cityID, 2) = 0
You can detect whether a number is even with the module operator (%), which gives the remainder after division by 2:
select * from your_table where cityID % 2= 0
The above query will give all the rows in which the cityID is divisible by 2
If you are interested in mod then it would be
select 6%2 -- results for this is 0
if you would want to select a number divided by 2 it will always return 0 for the perfect devisors.
if want the division the use the normal / operator as below
eg select 6/3
I used a slightly different approach. this is an event if you want a result of a zero or 1 if perfect divisor and zero otherwise
So my script is something like this
select case when #value<2 then 0 when #value%2 =0 then 1 else 0 end as myresult;
An example is as below for validating numbers between 1 and 20. You could amend it to fit your purpose
begin
declare #a int,#b int
set #a=1;
set #b = 20
while #a<=#b
begin
declare #value int
set #value =#a
select #value as myval, case when #value<2 then 0 when #value%2 =0 then 1 else 0 end
as myresult;
set #a=#a+1;
end
end

ISNUMERIC and TRY_PARSE in SQL Server [duplicate]

What is the best way to determine whether or not a field's value is an integer in SQL Server (2000/2005/2008)?
IsNumeric returns true for a variety of formats that would not likely convert to an integer. Examples include '15,000' and '15.1'.
You can use a like statement but that only appears to work well for fields that have a pre-determined number of digits...
select * where zipcode like '[0-9][0-9][0-9][0-9][0-9]'
I could write a user defined function that attempts to convert a varchar parameter to an int within a try/catch block but I'm checking with the community to see if someone has come across any succient methods to achieve this goal - preferably one that can be used within the where clause of a SQL statement without creating other objects.
Late entry that handles negative
ISNUMERIC(zipcode + '.0e0') --integer
ISNUMERIC(zipcode + 'e0') --decimal
For more see this
1 approach is
zipcode NOT LIKE '%[^0-9]%'
Double negatives, got to love 'em!
If SQL Server 2005+, I'd enable CLR and create the function to support regexes. For SQL Server 2000, see this article for creating a UDF to do the same thing.
Then I'd use the regex: ^\d{5}$
This expression gives 1 for an integer value and 0 otherwise
floor((floor(abs(zipcode)))/abs(zipcode))
Why not just use the following? I can't see to find any cases where it fails.
1 = integer
0 = not integer
null = non-numeric
DECLARE #TestValue nvarchar(MAX)
SET #TestValue = '1.04343234e5'
SELECT CASE WHEN ISNUMERIC(#TestValue) = 1
THEN CASE WHEN ROUND(#TestValue,0,1) = #TestValue
THEN 1
ELSE 0
END
ELSE null
END AS Analysis
It looks like this question needs an updated answer.
Limiting the answer to the question title:
where ISNUMERIC(zipcode) = 1
and zipcode - FLOOR(zipcode) = 0
Expounding based on the text of the question...
Currently-supported versions of SQL Server all support/include the TRY-CONVERT function.
declare #a varchar(100)
set #a = '-1.2a'
--set #a = '-1.2'
--set #a = '-1'
--set #a = '-1.0'
--set #a = '-0'
--set #a = '0'
--set #a = '1'
select #a as 'Value'
, ISNUMERIC(#a) as ISNUMERIC
, case when ISNUMERIC(#a) = 1 and #a - FLOOR(#a) = 0 then 1 else 0 end as ISINTEGER
, case when try_convert(int, #a) >= 0 and left(#a, 1) <> '-' then 1 else 0 end as ISWHOLENUMBER
, case when try_convert(int, #a) > 0 then 1 else 0 end as ISCOUNTINGNUMBER
You'll notice that TRY_CONVERT(INT, -1.0) returns NULL. So TRY_CONVERT(INT, #a) IS NOT NULL is not quite right for ISINTEGER.
case when ISNUMERIC(#a) = 1 and #a - FLOOR(#a) = 0 then 1 else 0 end as ISINTEGER
...works because if ISNUMERIC(#a) = 1 is false, FLOOR(#a) is not evaluated. Reversing the order...
case when #a - FLOOR(#a) = 0 and ISNUMERIC(#a) = 1 then 1 else 0 end as ISINTEGER
...generates an error when the value (#a) is not numeric.
So, for the case of zipcode, assuming you want to verify that a 5-digit zip code is a number and it must be 5 digits (so it can't be zero or less) and would never contain a decimal point (so you don't need to know if 12345.000 is an integer):
where try_convert(int, zipcode) > 0
and len(zipcode) = 5
I came up with the perfect answer for this on another StackO question.
It also proves you cannot use ".0e0" like one user suggests here.
It does so without CLR or non-scalar functions.
Please check it out: https://stackoverflow.com/a/10645764/555798
After moving to sql 2008, I was struggling with isnumeric('\8') returning true but throwing an error when casting to an integer. Apparently forward slash is valid currency for yen or won - (reference http://www.louiebao.net/blog/200910/isnumeric/)
My solution was
case when ISNUMERIC(#str) > 0 and not rtrim(#str) LIKE '[^0-9]%' and not rtrim(#str) LIKE '%[^0-9]' and not rtrim(#str) LIKE '[^0-9]%' then rtrim(#str) else null end
See whether the below code will help.
In the below values only 9, 2147483647, 1234567 are eligible as
Integer. We can create this as function and can use this.
CREATE TABLE MY_TABLE(MY_FIELD VARCHAR(50))
INSERT INTO MY_TABLE
VALUES('9.123'),('1234567'),('9'),('2147483647'),('2147483647.01'),('2147483648'), ('2147483648ABCD'),('214,7483,648')
SELECT *
FROM MY_TABLE
WHERE CHARINDEX('.',MY_FIELD) = 0 AND CHARINDEX(',',MY_FIELD) = 0
AND ISNUMERIC(MY_FIELD) = 1 AND CONVERT(FLOAT,MY_FIELD) / 2147483647 <= 1
DROP TABLE MY_TABLE
I did it using a Case statement:
Cast(Case When Quantity/[# of Days]= Cast(Quantity/[# of Days] as int) Then abs(Quantity/[# of Days]) Else 0 End as int)
To test whether the input value is an integer or not we can use SQL_VARIANT_PROPERTY function of SQL SERVER.
The following SQL Script will take input and test it whether the data type turns out to be integer or not
declare #convertedTempValue bigint, #inputValue nvarchar(255) = '1' --Change '1' to any input value
set #convertedTempValue = TRY_PARSE(#inputValue as bigint) --we trying to convert to bigint
declare #var3 nvarchar(255) = cast (SQL_VARIANT_PROPERTY(#convertedTempValue,'BaseType') as nvarchar(255)) --we using SQL_VARIANT_PROPERTY to find out datatype
if ( #var3 like '%int%')
begin
print 'value is integer'
end
else
begin
print 'value is non integer'
end
go
Really late to this but would this work?
select * from from table
where (ISNUMERIC(zipcode) = 0 OR zipcode like '%.%')
Filters out items that are integers.
Maybe you should only store integer data in integer datatypes.

Setting variables on CASE results in SQL?

I'm sure the answer is simple, but I have been searching for a while and can't seem to get this working ...
I am tring to set a variable based on a Case statement result.
So I am checking length of two columns
dbo.MY_TABLES.MY_RULESET,
dbo.MY_TABLES.MY_SPECIFICATION
My case statements check If length/75 is over 1 then we return 1. If under 1, then we return the value (under 1)
I then want to add these two results together and is where im getting problems when i need the addtion dependant on the case results.
Here is sample
Declare #SpecValue FLOAT
Declare #RuleValue FLOAT
SELECT
CAST(LEN(MY_SPECIFICATION) AS FLOAT)/75 as Score1,
CAST(LEN (MY_RULESET) AS FLOAT)/75 AS Score2,
CASE
WHEN (CAST(LEN(MY_SPECIFICATION) AS FLOAT)/75) >1 Then '1'
ELSE (Round(CAST(LEN(MY_SPECIFICATION) AS FLOAT)/75,2))
END as Spec1_RuleLength,
CASE
When (CAST(LEN (MY_RULESET) AS FLOAT)/75) >1 Then '1'
ELSE (Round(CAST(LEN (MY_RULESET) AS FLOAT)/75,2))
END as Eval2_RuleLength,
dbo.MY_TABLES.MY_RULESET,
dbo.MY_TABLES.MY_SPECIFICATION
FROM MY_TABLES
All columns in a SELECT clause are computed as if they're evaluated in parallel. This means that one column cannot depend on the value of another column computed in the same SELECT.
You might try moving the current query into a subselect:
SELECT Score1 + Score2 /* etc */
FROM (
SELECT
CAST(LEN(MY_SPECIFICATION) AS FLOAT)/75 as Score1,
CAST(LEN (MY_RULESET) AS FLOAT)/75 AS Score2,
CASE
WHEN (CAST(LEN(MY_SPECIFICATION) AS FLOAT)/75) >1 Then '1'
ELSE (Round(CAST(LEN(MY_SPECIFICATION) AS FLOAT)/75,2))
END as Spec1_RuleLength,
CASE
When (CAST(LEN (MY_RULESET) AS FLOAT)/75) >1 Then '1'
ELSE (Round(CAST(LEN (MY_RULESET) AS FLOAT)/75,2))
END as Eval2_RuleLength,
dbo.MY_TABLES.MY_RULESET,
dbo.MY_TABLES.MY_SPECIFICATION
FROM MY_TABLES
) t

Best equivalent for IsInteger in SQL Server

What is the best way to determine whether or not a field's value is an integer in SQL Server (2000/2005/2008)?
IsNumeric returns true for a variety of formats that would not likely convert to an integer. Examples include '15,000' and '15.1'.
You can use a like statement but that only appears to work well for fields that have a pre-determined number of digits...
select * where zipcode like '[0-9][0-9][0-9][0-9][0-9]'
I could write a user defined function that attempts to convert a varchar parameter to an int within a try/catch block but I'm checking with the community to see if someone has come across any succient methods to achieve this goal - preferably one that can be used within the where clause of a SQL statement without creating other objects.
Late entry that handles negative
ISNUMERIC(zipcode + '.0e0') --integer
ISNUMERIC(zipcode + 'e0') --decimal
For more see this
1 approach is
zipcode NOT LIKE '%[^0-9]%'
Double negatives, got to love 'em!
If SQL Server 2005+, I'd enable CLR and create the function to support regexes. For SQL Server 2000, see this article for creating a UDF to do the same thing.
Then I'd use the regex: ^\d{5}$
This expression gives 1 for an integer value and 0 otherwise
floor((floor(abs(zipcode)))/abs(zipcode))
Why not just use the following? I can't see to find any cases where it fails.
1 = integer
0 = not integer
null = non-numeric
DECLARE #TestValue nvarchar(MAX)
SET #TestValue = '1.04343234e5'
SELECT CASE WHEN ISNUMERIC(#TestValue) = 1
THEN CASE WHEN ROUND(#TestValue,0,1) = #TestValue
THEN 1
ELSE 0
END
ELSE null
END AS Analysis
It looks like this question needs an updated answer.
Limiting the answer to the question title:
where ISNUMERIC(zipcode) = 1
and zipcode - FLOOR(zipcode) = 0
Expounding based on the text of the question...
Currently-supported versions of SQL Server all support/include the TRY-CONVERT function.
declare #a varchar(100)
set #a = '-1.2a'
--set #a = '-1.2'
--set #a = '-1'
--set #a = '-1.0'
--set #a = '-0'
--set #a = '0'
--set #a = '1'
select #a as 'Value'
, ISNUMERIC(#a) as ISNUMERIC
, case when ISNUMERIC(#a) = 1 and #a - FLOOR(#a) = 0 then 1 else 0 end as ISINTEGER
, case when try_convert(int, #a) >= 0 and left(#a, 1) <> '-' then 1 else 0 end as ISWHOLENUMBER
, case when try_convert(int, #a) > 0 then 1 else 0 end as ISCOUNTINGNUMBER
You'll notice that TRY_CONVERT(INT, -1.0) returns NULL. So TRY_CONVERT(INT, #a) IS NOT NULL is not quite right for ISINTEGER.
case when ISNUMERIC(#a) = 1 and #a - FLOOR(#a) = 0 then 1 else 0 end as ISINTEGER
...works because if ISNUMERIC(#a) = 1 is false, FLOOR(#a) is not evaluated. Reversing the order...
case when #a - FLOOR(#a) = 0 and ISNUMERIC(#a) = 1 then 1 else 0 end as ISINTEGER
...generates an error when the value (#a) is not numeric.
So, for the case of zipcode, assuming you want to verify that a 5-digit zip code is a number and it must be 5 digits (so it can't be zero or less) and would never contain a decimal point (so you don't need to know if 12345.000 is an integer):
where try_convert(int, zipcode) > 0
and len(zipcode) = 5
I came up with the perfect answer for this on another StackO question.
It also proves you cannot use ".0e0" like one user suggests here.
It does so without CLR or non-scalar functions.
Please check it out: https://stackoverflow.com/a/10645764/555798
After moving to sql 2008, I was struggling with isnumeric('\8') returning true but throwing an error when casting to an integer. Apparently forward slash is valid currency for yen or won - (reference http://www.louiebao.net/blog/200910/isnumeric/)
My solution was
case when ISNUMERIC(#str) > 0 and not rtrim(#str) LIKE '[^0-9]%' and not rtrim(#str) LIKE '%[^0-9]' and not rtrim(#str) LIKE '[^0-9]%' then rtrim(#str) else null end
See whether the below code will help.
In the below values only 9, 2147483647, 1234567 are eligible as
Integer. We can create this as function and can use this.
CREATE TABLE MY_TABLE(MY_FIELD VARCHAR(50))
INSERT INTO MY_TABLE
VALUES('9.123'),('1234567'),('9'),('2147483647'),('2147483647.01'),('2147483648'), ('2147483648ABCD'),('214,7483,648')
SELECT *
FROM MY_TABLE
WHERE CHARINDEX('.',MY_FIELD) = 0 AND CHARINDEX(',',MY_FIELD) = 0
AND ISNUMERIC(MY_FIELD) = 1 AND CONVERT(FLOAT,MY_FIELD) / 2147483647 <= 1
DROP TABLE MY_TABLE
I did it using a Case statement:
Cast(Case When Quantity/[# of Days]= Cast(Quantity/[# of Days] as int) Then abs(Quantity/[# of Days]) Else 0 End as int)
To test whether the input value is an integer or not we can use SQL_VARIANT_PROPERTY function of SQL SERVER.
The following SQL Script will take input and test it whether the data type turns out to be integer or not
declare #convertedTempValue bigint, #inputValue nvarchar(255) = '1' --Change '1' to any input value
set #convertedTempValue = TRY_PARSE(#inputValue as bigint) --we trying to convert to bigint
declare #var3 nvarchar(255) = cast (SQL_VARIANT_PROPERTY(#convertedTempValue,'BaseType') as nvarchar(255)) --we using SQL_VARIANT_PROPERTY to find out datatype
if ( #var3 like '%int%')
begin
print 'value is integer'
end
else
begin
print 'value is non integer'
end
go
Really late to this but would this work?
select * from from table
where (ISNUMERIC(zipcode) = 0 OR zipcode like '%.%')
Filters out items that are integers.
Maybe you should only store integer data in integer datatypes.

How do I create an If-Then-Else in T-SQL

I have some negative values coming back from a query. I would like them to just be zero.
How do I write a condition in my sql query that returns zero if the value is below a certain value.
sol:
CASE WHEN CONVERT(float,dt.FQI53X02_101) < 1.3 THEN 0 ELSE CONVERT(float,dt.FQI53X02_101) END AS FQI53X02_101
You dont use If-Then-Else in the actual query (you can use them but thats something else)...
What you use is a Case statement... Try this
Select
Case When [Value] < 0 Then 0 Else [Value] End
From
Example
If you want it as part of your query, wrap the return inside a CASE statement. Example from MSDN is below
SELECT 'Price Category' =
CASE
WHEN price IS NULL THEN 'Not yet priced'
WHEN price < 10 THEN 'Very Reasonable Title'
WHEN price >= 10 and price < 20 THEN 'Coffee Table Title'
ELSE 'Expensive book!'
END,
CAST(title AS varchar(20)) AS 'Shortened Title'
FROM titles
ORDER BY price
( ABS(Value) + Value ) / 2
edit - this doesn't work now the question has changed