Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum varchar datatype by converting varchar into float

Tags:

database

mysql

I have a column 'amount' which is in 'varchar' datatype in my table 'tbl1'. Now I have to calculate total amount of that column (I know I can modify column for my table but I have to follow some procedure to keep it as 'varchar' . but result must be return in float datatype.

I have written following query as:

Select sum(amount) from tbl1;

it gives an error :

Conversion failed when converting varchar datatype into int

so tried this one query also:

select sum(convert(float, amount)) from tbl1;

but I got error.

like image 321
Sujit Libi Avatar asked Sep 09 '15 09:09

Sujit Libi


People also ask

Can you convert varchar to float?

If you are planning to convert varchar to float you should know that these two data types are not compatible with each other. In the earlier versions of SQL Server you had to use CASE, ISNUMERIC & CONVERT to convert varchar to float but in SQL Server 2012, you can do it with just one function TRY_CONVERT.

Can we do sum on varchar?

Operand data type varchar is invalid for sum operator.


1 Answers

Try like this:

SELECT sum(CAST(amount AS UNSIGNED)) FROM tbl1

Note that UNSIGNED and SIGNED are used for Integer. If your data may contain decimal values then you can instead try to use decimal like this:

SELECT sum(CAST(amount AS DECIMAL(10,2))) FROM tbl1
like image 122
Rahul Tripathi Avatar answered Oct 19 '22 23:10

Rahul Tripathi