Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Varchar invalid for Sum operator

I have a table called Cos and the datatype of Amt is Float and sample data looks like:

Acct  Period  F_year   Amt
Detf  1       2011     Null
Detf  2       2011     Null
Detf  3       2011     1669.57
FTE   1       2011     3205.11
FTE   2       2011     0
FTE   3       2011     Null

I wrote a query like:

Select Acct,Period,F_year, Sum(AMT) as Amt
from dbo.Cos
Group By Acct,Period,F_year
Where Amt is not null

But i am getting this error:

Msg 8117, Level 16, State 1, Line 1
Operand data type varchar is invalid for sum operator.

Can anyone help me?

like image 662
peter Avatar asked Nov 28 '22 07:11

peter


2 Answers

Try doing this:

Select Acct,Period,F_year, Sum(isnull(cast(AMT as float),0)) as Amt
from dbo.Cos
Group By Acct,Period,F_year
like image 111
Icarus Avatar answered Dec 03 '22 19:12

Icarus


Apparently, the value "1669.57" is a string. So what does it mean to add this value to another?

The error message is correct: It's not valid to add text values together. If it was valid, I could not tell what the result should be.

You should either change your column type to a numeric type, or convert it somehow before trying to add it.

like image 31
Jonathan Wood Avatar answered Dec 03 '22 19:12

Jonathan Wood