Reputation: 797
I have an Oracle table that shows a column 'Received Quantity' as a string. How do I remove the last two letters in that string and convert the rest to a number?
Select receipt_number
,item_name
,received_quantity
from item_table
The result is:
+-----------+----------+-------+
| Rcpt 01|Kool GLue |234CS |
+-----------+----------+-------+
| Rcpt 02|Red GLue |10CS |
+-----------+----------+-------+
| Rcpt 03|Bad GLue |1000CS |
+-----------+----------+-------+
I need help with code to remove the 'CS' in the field and convert the numbers to a number and then calculate the sum of all those numbers.
Eventually, I want to Calculate the Sum of number of Cases for all those items.
The code I'm trying is:
Select receipt_number
,item_name
,SUM (to_number(cast(received_quantity, -2)))
from item_table
group by receipt_number, item_name
Upvotes: 0
Views: 2171
Reputation:
The most robust way is to simply remove any character that is not a number using regexp_replace()
:
Select receipt_number,
item_name,
SUM(to_number(regexp_replace(received_quantity, '[^0-9]', ''))) as quantity
from item_table
group by receipt_number, item_name;
That would also cleanup strings like CS1234
Upvotes: 2
Reputation: 10226
That's the way I do it
Select receipt_number
,item_name
, SUM(TO_NUMBER(TRIM(REPLACE(received_quantity,'CS'))))
from item_table
group by receipt_number, item_name
There are many others
Upvotes: 1
Reputation: 6693
You can use SUBSTRING
so answer can be:
Select receipt_number
,item_name
,SUM (to_number(cast(SUBSTR(received_quantity, 1, LENGTH(received_quantity) - 2), -2)))
from item_table
group by receipt_number, item_name
Upvotes: 0