Problem with max() in sql server - sql

I have alphanumeric values like. XYZ1,XYZ2......XYZ11, XYZ12 and so on, now I want to select only the Max numeric value, i.e. 12 here.
I tried-
select max(REPLACE(ID,'XYZ','')) from myTable;
but this is returning 9. why?

Try converting to INT before max
select max(cast(REPLACE(ID,'XYZ','') as int)) from myTable;

It's still treating your value as a string instead of a number. Try:
select max(CAST(REPLACE(ID,'XYZ','') AS INT) from myTable;

Because you're still comparing strings. The fact that they contain only numeric digits doesn't mean that they're not strings. You need to convert them:
SELECT MAX(CAST(REPLACE(id, 'XYZ', '') AS INT)) FROM My_Table

Another method is
select max(REPLACE(ID,'XYZ','')*1) from myTable

Related

How do I extract the last 4 digits of numerical value?

How can I extract the last for digits from a number in Microsoft SQL Server? For example '6789' from a number like '123456789'.
I just want to keep the last 4 numbers.
If you are starting with a number, you are asking for the modulo operator. This generally has one of two syntaxes. SQL Server uses:
select col % 10000
An alternative syntax in other databases is:
select mod(col, 10000)
You can use right function, example for you:
select right('123456789',4)
One more approach using SUBSTRING.
DECLARE #table table(a varchar(30))
insert into #table
values ('12345678')
SELECT SUBSTRING(a,len(a) - 3, 4) from #table
5678

order clause for varchar ranges

I currently have a column in db with few ranges storaged as varchar, such as:
0-499
1000-1199
500-999
How do I order these ranges like the following:
0-499
500-999
1000-1199
Thanks in advance
If you want to be tricky, you can do:
order by cast(replace(col, '-', '.') as decimal(30, 15))
This replaces the hyphen with a decimal point, converts to a numeric value, and uses that for sorting. This should work in just about any database.
This is not perfect, because it does not really order by the second number of the range correctly. But the first number would need to exactly match (and for some reason, that seems unlikely to me base on your sample data).
Order by the characters before the hyphen, converted to an integer.
You can useorder by clause with left() function :
order by cast(left(n, charindex('-', n)-1) as int);
However, the preceding order by cluase has int conversation, if you have decimal value before hyphen then use decimal instead
if these are the only values:
order by
case varcharcol when '0-100' then 1
when '500-1000' then 2
when '1000-1199' then 3
end
create table #temp1(id int,range varchar(50))
insert into #temp1(id,range)
values (1,'0-499'),(2,'1000-1199'),(3,'500-999')
select * from #temp1 order by cast(replace(range, '-', '.') as decimal(30, 15))
id range
1 0-499
3 500-999
2 1000-1199
select * from #temp1 order by cast (substring(range,0,charindex('-',range)) as int)
id range
1 0-499
3 500-999
2 1000-1199

SQL Server - How to use convert with ISNULL

Something like the example below:
SELECT SSN, Name, CONVERT(VARCHAR(50), Hours) ISNULL(Hours, '')
where I want to convert an int to varchar and at the same time set the null values as an empty string. How can I do to make this possible?
ISNULL(CONVERT(VARCHAR(50), Hours), '')
An alternative option if you are on 2012+ would be to use
SELECT CONCAT(Hours,'')
which has the same end result of converting to string and returning empty string instead of NULL.
Wrap your convert in the isnull;
SELECT
SSN
,Name
,ISNULL(CONVERT(VARCHAR(50), Hours), '')
This way it will allow for the nulls to be pulled on the conversion, you won't be able to do the isnull inside the convert as a zero length character won't be compatible with an int field (or other number only field).

DB2 SQL Convert Decimal to Character with Padded Zeros

How can I convert my DECIMAL(11) field from 12345678 to a character value of 00012345678?
Only use the DIGITS function, because this verifies the length of the field numeric or decimal, etc and completes with zeros to the left when is necessary.
SELECT DIGITS(FIELD) FROM ...
The length of the resulting string is always:
5 if the argument is a small integer
10 if the argument is a large integer
19 if the argument is a big integer
Based on your comment in #Mr Fuzzy Botton's answer, I'm guessing you're on DB2 for i, which does not have the LPAD function. You could instead use a combination of the REPEAT and RIGHTfunctions:
SELECT RIGHT(REPEAT('0', 11) || LTRIM(CHAR(your_field)), 11)
FROM your_table
Using http://pic.dhe.ibm.com/infocenter/dzichelp/v2r2/topic/com.ibm.db2.doc.sqlref/castsp.htm for details on CAST
and http://pic.dhe.ibm.com/infocenter/dzichelp/v2r2/topic/com.ibm.db2z10.doc.sqlref/src/tpc/db2z_scalarfunctionsintro.htm for string functions,
I assume this should do the trick -
SELECT LPAD( CAST(FIELD AS CHAR(11)) ,11,'0') AS PADDEDFIELD
Don't know if you've worked it out, however try this:
SELECT LPAD( DIGITS( fieldName ), 11, '0') ) as paddedFieldName FROM yourTable
The LPAD is the left padding, but the DIGITS function was the only way I got DB2 to treat the numeric value like a string.
My LeftPad function without LeftPad function
REPEAT('0', 4-length(MY_COLUMN_VALUE))||CHAR(MY_COLUMN_VALUE) as NEW_COLUMN
MY_COLUMN_VALUE NEW_COLUMN
1 0004
23 0023
testing ...
SELECT '32' MY_VALUE, REPEAT('0', 4-length('23'))||CHAR('23') as LEFTPAB_MY_VALUE FROM sysibm.sysdummy1
If this is DB2 for i, and myColumn data type is DECIMAL with precision (11) and scale (0), then:
SELECT digits( myColumn ) FROM sysibm.sysdummy1
will return:
....+....1.
DIGITS
00001234567
Changing the number of leading zeros could be done in many ways. CASTing to a different precision before using DIGITS() is one way.
SELECT SUBSTRING(
CHAR(100000000000+fieldName),
2,11
) as paddedFieldName
FROM yourTable
I only wanted to define my field once in the select statement so the above worked for me and is tidy
I just went the other direction: cast(field as int)
Try this for your field x:
substr(digits(x), 33 - length(x), length(x) )
From Numeric 8,0 (datenumfld=20170101) to 01/01/2017 This works for me:
DATE(TO_DATE(CHAR(datenumfld), 'YYYYMMDD')) as YourDate

How to give select digit after decimal point?

In database there is column amount which datatype is money. I want to select that row only with two digit after decimal. for this how to write the query?
My query is like this:
SELECT AMOUNT FROM DETAIL_PAGE.
I want to modify this query so that it selects two digits after decimal point.
SELECT AMOUNT - FLOOR(AMOUNT) FROM DETAIL_PAGE
That will get you just the decimal though. I think you want
SELECT FORMAT(AMOUNT, 2) FROM DETAIL_PAGE
Or without commas:
SELECT REPLACE(FORMAT(AMOUNT, 2), ',', '') FROM DETAIL_PAGE
Not sure if this is SQL standard and works elsewhere, but in Oracle you can say
select round(amount,2) from detail_page
-- round(12.345, 2) would return 12.35
or
select trunc(amount,2) from detail_page
-- trunc(12.345, 2) would return 12.34