Replace a range of values in an SQL table to a single value - sql

I am trying to replace a range of values with a string. I know how to do it with the replace function but that, as far as I know, requires them to be done one at a time.
Is there a way to select a range of values, for example (1-200), and replace them with a singular string value say "BLANK"?
I have tried WHEN, THEN and SET but get a syntax error near WHEN or SET as I try these.
Base Code Idea
Select DATA
WHEN DATA >= 1 THEN 'BLANK'
WHEN DATA <200 THEN 'BLANK
END
FROM DATABANK
Thanks!

Is this what you want?
select data,
case when data not between 1 and 200 then data end as new_data
from databank
What this does is take the integer value of data, and replace any value that's in the 1-200 range with null values, while leaving other values unchanged. The result goes into column new_data.
The assumption here is that data is a number - so the alternative value has to be consistent with that datatype (string 'BLANK' isn't): I went for null, which is consistent with any datatype, and is the default value returned by a case expression when no branch matches.
If you wanted something else, say 0, you would do:
select data,
case when data between 1 and 200 then 0 else data end as new_data
from databank

Related

sql server logic to workout the right most position of the numeric field will have a sign OVER it designating positive or negative

Example of the data in csv
Column_header
000000025000{
000000007185E
The doucmention I have
*The right most position of the numeric field will have a sign OVER it
designating positive or negative.
Example of Data
I dont understand how write the logic to support the the symbol,number,letter to get the correct value.
I'd create a table (or view) with the static mapping of character-value, meaning:
Symbol
Value
J
-1
A
+1
about the data rows themselves, it seems to me there is always a symbol at the end, therefore you can split the data into two columns, value, and symbol...
I have no idea about how the data are inserted but it seems logically easy
SELECT
_YourValue_
,LEFT(_YourValue_, LENGTH(_YourValue_)-1) as Value
,RIGHT(_YourValue_, 1) as Symbol
FROM _Whatever_
you can also cast to whatever datatype is correct for those data.
Finally you can join the tables and show/calculate whatever is needed
select value , if(value LIKE '%{%' or value LIKE '%J%' or value LIKE '%E%' or value LIKE '%C%',concat(SUBSTRING(value,1,char_length(value)-1),'+'),concat(SUBSTRING(value,1,char_length(value)-1),'-')) as new_value from yourtablename
Output
value
New Value
000000025000{
000000025000+
000000007185E
000000007185+
Add all other character on first parameter of if clause for positive designation.

How do I return a value if the string is between 6 and 10 characters in SQL?

I have a column of data where the length of each entry varies, e.g
12345678
123
AA
12345678912345
......
I wish to return value if the string length is between 6 and 10. If it's less than 6 or greater than 10, then return a blank.
In my example I would have one value 12345678 showing and three blanks.
You can use LEN function to test length of column value and CASE to return the value you want (supposing the column name is "field"):
SELECT CASE WHEN (LEN(field) >= 6 AND LEN(field) <= 10)
THEN field
ELSE '' END as 'YourField'
FROM nameoftable
To get it without the blanks you would do:
SELECT FIELD
FROM table_name
WHERE LEN(FIELD) >= 6 AND LEN(FIELD) <= 10
If you don't mind having the output for each row presented in a new column, you could do the following:
Assume the data you have is stored in "colA" in a table called "yourTable", then:
select case when len(colA) between 6 and 10 then colA else '' end as colB from yourTable
The syntax above will work in Microsoft SQL Server. You may have to tweak to find the equivalent length and comparison functions in whichever RDMS you happen to be using.
Another issue you may face is data type conversion issues. If your colA is defined as a character field, the code above should work without issue (i.e., you'll get blanks back for values outside of your test criteria). If colA is numeric, then using '' to insert a blank may actually return 0. It's up to you to decide how you want to handle this issue.

PostgreSQL - Assign integer value to string in case statement

I need to select one and only 1 row of data based on an ID in the data I have. I thought I had solved this (For details, see my original question and my solution, here: PostgreSQL - Select only 1 row for each ID)
However, I now still get multiple values in some cases. If there is only "N/A" and 1 other value, then no problem.. but if I have multiple values like: "N/A", "value1" and "value2" for example, then my case statement is not sufficient and I get both "value1" and "value2" returned to me. This is the case statement in question:
CASE
WHEN "PQ"."Value" = 'N/A' THEN 1
ELSE 0
END
I need to give a unique integer value to each string value and then the problem will be solved. The question is: how do I do this? My first thought is to somehow convert the character values to ASCII and sum them up.. but I am not sure how to do that and also worried about performance. Is there a way to very simply assign a value to each string so that I can choose 1 value only? I don't care which one actually... just that it's only 1.
EDIT
I am now trying to create a function to add up the ASCII values of each character so I can essentially change my case statement to something like this:
CASE
WHEN "PQ"."Value" = 'N/A' THEN 9999999
ELSE SumASCII("PQ"."Value")
END
Having a small problem with it though.. I have added it as a separate question, here: PostgreSQL - ERROR: query has no destination for result data
EDIT 2
Thanks to #Bohemian, I now have a working solution, which is as follows:
CASE
WHEN "PQ"."Value" = 'N/A' THEN -1
ELSE ('x'||LPAD(MD5("PQ"."Value"),16,'0'))::bit(64)::bigint
END DESC
This will produce a "unique" number for each value:
('x'||substr(md5("PQ"."Value"),1,8))::bit(64)::bigint
Strictly speaking, there is a chance of a collision, but it's very remote.
If the result is "too big", you could try modulus:
<above-calculation> % 10000
Although collisions would then be a 0.01% chance, you should try this formula against all known values to ensure there are no collisions.
If you don't care which value gets picked, change RANK() to ROW_NUMBER(). If you do care, do it anyway, but also add another term after the CASE statement in ORDER BY, separated by a comma, with the logic you want - for example if you want the first value alphabetically, do this:
...
ORDER BY CASE...END, "PQ"."Value")
...

Sql parse column as int and check if it is within range

I've used the top voted answer from here to check if a cell value is an integer. But I also need to do a range check on it.
SELECT * FROM Table
WHERE (dbo.IsInteger(FieldName) = 1) AND FieldName > 400 AND FieldName < 500
But this returns a conversion error, as some of the cells in the column contains text. So, is it possible to get a subset, that is only results from the IsInteger query, and then do a range check on the result?
You need to wrap it in a CASE expression. I've altered the query slightly to use BETWEEN to avoid having to repeat the expression.
SELECT * FROM Table
WHERE CASE WHEN dbo.IsInteger(FieldName) = 1
THEN FieldName END BETWEEN 401 AND 499
The result of the expression will be NULL when dbo.IsInteger(FieldName) <> 1 which will not match the BETWEEN predicate.
Of course this is completely unsargable but so is your original query.

Conditionally branching in SQL based on the type of a variable

I'm selecting a value out of a table that can either be an integer or a nvarchar. It's stored as nvarchar. I want to conditionally call a function that will convert this value if it is an integer (that is, if it can be converted into an integer), otherwise I want to select the nvarchar with no conversion.
This is hitting a SQL Server 2005 database.
select case
when T.Value (is integer) then SomeConversionFunction(T.Value)
else T.Value
end as SomeAlias
from SomeTable T
Note that it is the "(is integer)" part that I'm having trouble with. Thanks in advance.
UPDATE
Check the comment on Ian's answer. It explains the why and the what a little better. Thanks to everyone for their thoughts.
select case
when ISNUMERIC(T.Value) then T.Value
else SomeConversionFunction(T.Value)
end as SomeAlias
Also, have you considered using the sql_variant data type?
The result set can only have one type associated with it for each column, you will get an error if the first row converts to an integer and there are strings that follow:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value 'word' to data type int.
try this to see:
create table testing
(
strangevalue nvarchar(10)
)
insert into testing values (1)
insert into testing values ('word')
select * from testing
select
case
when ISNUMERIC(strangevalue)=1 THEN CONVERT(int,strangevalue)
ELSE strangevalue
END
FROM testing
best bet is to return two columns:
select
case
when ISNUMERIC(strangevalue)=1 THEN CONVERT(int,strangevalue)
ELSE NULL
END AS StrangvalueINT
,case
when ISNUMERIC(strangevalue)=1 THEN NULL
ELSE strangevalue
END AS StrangvalueString
FROM testing
or your application can test for numeric and do your special processing.
You can't have a column that is sometimes an integer and sometimes a string. Return the string and check it using int.TryParse() in the client code.
ISNUMERIC. However, this accepts +, - and decimals so more work is needed.
However, you can't have the columns as both datatypes in one go: you'll need 2 columns.
I'd suggest that you deal with this in your client or use an ISNUMERIC replacement
IsNumeric will get you part of the way there. You can then add some further code to check whether it is an integer
for example:
select top 10
case
when isnumeric(mycolumn) = 1 then
case
when convert(int, mycolumn) = mycolumn then
'integer'
else
'number but not an integer'
end
else
'not a number'
end
from mytable
To clarify some other answers, your SQL statement can't return different data types in one column (it looks like the other answers are saying you can't store different data types in one column - yours are all strign represenations).
Therefore, if you use ISNUMERIC or another function, the value will be cast as a string in the table that is returned anyway if there are other strigns being selected.
If you are selecting only one value then it could return a string or a number, however your front end code will need to be able to return the different data types.
Just to add to some of the other comments about not being able to return different data types in the same column... Database columns should know what datatype they are holding. If they don't then that should be a BIG red flag that you have a design problem somewhere, which almost guarantees future headaches (like this one).