Duration column in the table is given with 'varchar' data type. It contains decimal values. So I am trying to cast varchar to float/numeric/decimal/double/double precision. But none of those works. why is it not working?
select runner_id, sum(case when cast(duration as decimal) <> '' then 1 else 0 end) as delivered, count(order_id) as total_orders
from t_runner_orders group by runner_id
The reason it's not working is because your duration column contains values which cannot be cast to a numeric type. The specific value throwing the error is an empty string. Also, you shouldn't be comparing a numeric type to an empty string.
Also, if you're comparing a varchar column to a character value in your CASE statement, why are you trying to cast it to a numeric type at all?
For what you're doing here, I would just write it as CASE WHEN duration <> '' THEN 1 ELSE 0 END
And if you do need to cast it to a numeric type at some point, the way to do that would be something like CASE WHEN duration = '' THEN NULL ELSE cast(duration AS DECIMAL) END
(asuming that empty strings are the only values in your column which cannot be cast to decimal)
The problem is you are doing the CAST
before the <> ''
. The cast
fails as there are empty strings in the field. You have several choices:
Use NULL
instead of '' in field.
Do duration <> ''
Last and probably the best long term solution change the column type to numeric.
You can translate '' to null using NULLIF
in the cast.
cast(nullif(duration,'') as decimal) is not null
However this will not solve you basic problem which is "varchar' data type. It contains decimal values" NO it does not it contains a string which you hope are decimal values , but nothing prohibits putting 'zero.zero' into it - distinctly not a decimal value. I will go @AdrianKlaver one step further.
3. The only long term solution change the column type to numeric.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.