SQL SELECT statement with Cast, LPad and Max - sql

Are there any issues with this select statement ??
SELECT SUBSTR(FIELD_A,10,3) as MOVID,
MAX(LPAD((CAST(SUBSTR(FIELD_A,-3,3) as INT) + 1 ), 3, 0)) as NEXTMOVID
FROM ...
The field is a VARCHAR2.
I want to maintain 3 characters(which are numbers) and add 1 and concatenate with another varchar2
retrieve a portion of the FIELD_A
convert is to an integer
add 1
Left Pad it to 3 characters with 0
Grab the MAX
Later on I concatenate with another field
Wondering if there was a better way to do this ??

As I understand, you need following:
SELECT SUBSTR(FIELD_A,10,3) as MOVID,
to_char(to_number(SUBSTR(FIELD_A, -3, 3)) + 1), '000') as NEXTMOVID
FROM ...

Related

SQL Server - Dynamically Filling the column Values with 0's as per the fixed length

I have a column with the given values
MRN
1946
456
27
557
The column values length is fixed.
If at all any value is less than 6characters,then it should concate 0's to the left and make it 6characters length.
The desired output is
MRN
001946
000456
000027
000557
This is called left paddings. In SQL Server, this is typically done with more basic string operations:
select right(replicate('0', 6) + mrn, 6)
If mrn is a number, then use the concat() function:
select right(concat(replicate('0', 6), mrn), 6)
You can also use the FORMAT function for this. (Demo)
SELECT FORMAT(MRN ,'D6')
FROM YourTable
Change the number 6 to whatever your total length needs to be:
SELECT REPLICATE('0',6-LEN(EmployeeId)) + EmployeeId
If the column is an INT, you can use RTRIM to implicitly convert it to a VARCHAR
SELECT REPLICATE('0',6-LEN(RTRIM(EmployeeId))) + RTRIM(EmployeeId)
And the code to remove these 0s and get back the 'real' number:
SELECT RIGHT(EmployeeId,(LEN(EmployeeId) - PATINDEX('%[^0]%',EmployeeId)) + 1)
We can achieve this by adding leading zero's
select RIGHT('0000'+CAST(MRN AS VARCHAR(10)),6)

ORA-01722: invalid number - value with two decimals

I'm trying to get the max value from a text field. All but two of the values are numbers with a single decimal. However, two of the values have something like 8.2.10. How can I pull back just the integer value? The values can go higher than 9.n, so I need to convert this field into a number so that I can get the largest value returned. So all I want to get back is the 8 from the 8.2.1.
Select cast(VERSION as int) is bombing out because of those two values with a second . in them.
You may derive by using regexp_substr with \d pattern :
with tab as
(
select regexp_substr('8.2.1', '\d', 1, 1) from dual
union all
select regexp_substr('9.0.1', '\d', 1, 1) from dual
)
select * from tab;
For Oracle you must attend the value as string for retire only the part before the dot. Ex:
SELECT NVL( SUBSTR('8.2.1',0, INSTR('8.2.1','.')-1),'8.2.1') AS SR FROM DUAL;
Check than the value is repeated 3 times in the sentence, and if the value is zero or the value didn't have decimal part then it will return the value as was set.
I had to use T-SQL rather PL/SQL, but the idea is the same:
DECLARE #s VARCHAR(10);
SELECT #s='8.2.1';
SELECT CAST(LEFT(#s, CHARINDEX('.', #s) - 1) AS INT);
returns the integer 8 - note that it won't work if there are no dots because it takes the part of the string to the left of the first dot.
If my quick look at equivalent functions was correct, then in Oracle that would end up as:
SELECT CAST(SUBSTR(VERSION, 1, INSTR(VERSION, '.') - 1) AS INT)

Having an issue with select max

I have a column that has entries such as 86D12345, 86A12345, etc. I need to be able to do 2 things:
Select MAX value of this column
Add 1 to get the next number
This column is nvarchar, so I assume I will have to utilize the substring function plus the select MAX, but cannot seem to get the results. Example is when I run this query:
select substring(convert(numeric(5,0), certno),4,len(certno))+1 from maxcertno
I get:
Argument data type numeric is invalid for argument 1 of substring function.
Same error with cast
Any ideas?
Assuming the format if fixed like nn N nnnnn (without the blanks).
This gives the next value (12346):
cast(substring(certno, 4, len(certno)) as int) + 1
And this gives the whole string incremented by 1 (86D12346):
left(certno, 3) + cast(cast(substring(certno, 4, len(certno)) as int) + 1 as nvarchar(50))
With the max function:
select
cast(substring(max(certno), 4, len(max(certno))) as int) + 1,
left(max(certno), 3) + cast(cast(substring(max(certno), 4, len(max(certno))) as int) + 1 as nvarchar(50))
from YourTable
The last is probably not a good solution in that it's repeating max all over the query. Better to get the max value first and then apply the logic. Or maybe make it a function or stored proc.

How I can get the first 3 digits in 123456 Numbers in sql?

I have field called CallingParty in My CDR table it contains data like this:
CallingParty
------------
267672668788
I want to select the first 3 number of each of those numbers like
CallingParty
------------
267
if CallingParty is of type int:
SELECT CAST(LEFT(CallingParty, 3) AS INT)
From CDR
SQL Server has a Left() function, but it works best on strings. (varchar/char in SQL)
Select left(cast(267672668788 as varchar), 3)
Use this query:
SELECT SUBSTRING(CAST(CallingParty AS VARCHAR(50)), 1, 3) FROM [CDR]
If the data length does not change then you can always divide by 10 * the digits you have
SELECT FLOOR(267672668788 / 1000000000)
=267
Try this:
SELECT Substring(callingparty, 1, Length(callingparty) - 9)
FROM cdr;

Remove trailing zero from decimal number

I have a one database table field called Amount which type is decimal(18,6). so it is stored in database up to 6 decimal points like 9.786534 But while retrieving that field using select query i have to take care like following
Remove trialling zero e.g if number is 9.230000 then result is only 9.23
If decimal points are all zero then only remove only four trialling zero e.g If number is 9.000000 then result is 9.00
Result is up to 2 decimal point if there are trialling zero.
If we write simple query like
select TOP 1 Amount From EmployeeMaster
then it gives 9.230000
but my intension is to remove trailing zero..
Please help me..
It works for removing trailing zeros, but I am still not able to convert 9 to 9.00 in this method.
Declare #myvalue varchar(50),
#Price Varchar(50)
Set #Price = '9.230000'
set #Myvalue = reverse(substring(#Price,patindex('%.%',#Price)+1,len(#Price)))
SELECT
case
When patindex('%.%[1-9]%',#price) = 0 Then
substring(#price,1,patindex('%.%',#price)-1)
else
substring(#price,1,patindex('%.%',#price)-1) + '.' + Reverse(substring(#Myvalue,patindex('%[1-9]%',#Myvalue),len(#Myvalue)))
END
Coming from decimal(18,6) you could do...
select cast(Amount as decimal(18,2))
Most databases that support the CAST function will round the number while converting it. On SQLServer this is what I would do if I wanted rounding.
If what you actually want is a string with only two digits after the decimal then you could
select cast((Amount as decimal(18,2)) as nvarchar)
nvarchar is SQLServer's variable length unicode type. Databases do not agree much on string types. Your database may have a different one. The rest of that sql is ANSI standard. Not all dbs support that either but many do.
This should work
SELECT CAST(REPLACE(RTRIM(REPLACE(CAST(CAST(33.9082976 AS DECIMAL(38,8)) AS NVARCHAR(256)),'0',' ')),' ','0') AS FLOAT)
Does this work?
select TOP 1 ROUND(Amount, 2) From EmployeeMaster
TRY below mentioned code.
SELECT TOP 1 CONVERT(DECIMAL(10,2),Amount) From EmployeeMaster
Hope it will work as expected.
An alternative approach:
1) convert the decimal to a string;
2) split the string into 2 parts, separating the last 4 characters from the rest of the string;
3) remove trailing zeros from the last 4 characters;
4) concatenate the two parts back.
WITH data (V) AS (SELECT CAST(9.786534 AS decimal(18,6))
UNION ALL
SELECT CAST(9.78653 AS decimal(18,6))
UNION ALL
SELECT CAST(9.7800 AS decimal(18,6))
UNION ALL
SELECT CAST(9.7 AS decimal(18,6))
UNION ALL
SELECT CAST(9.00000 AS decimal(18,6))
)
, AsString (V) AS (SELECT CAST(V AS varchar) FROM data)
, Split (L, R) AS (SELECT LEFT(V, LEN(V) - 4), RIGHT(V, 4) FROM AsString)
, Adjusted AS (SELECT L,
REPLACE(RTRIM(REPLACE(R, '0', ' ')), ' ', '0') AS R
FROM Split)
SELECT Result = L + R FROM Adjusted
The output of the above script is:
Result
--------
9.786534
9.78653
9.78
9.70
9.00
I guess using patindex in your case:
CASE WHEN FLOOR(Amount) <> CEILING(Amount) THEN
LTRIM(SUBSTRING(STR(Amount, 18, 6), 1, LEN(STR(Amount, 18, 6)) - PATINDEX('%[^0]%', REVERSE(str(Amount, 18, 6))) + 1))
ELSE STR(Amount,18,2)
END
for a decimal(18,6) field this should work:
select trim(to_char(Amount, '999999999999999999.99')) from EmployeeMaster
(at least for Oracle, not sure about other types)