By
Published: 30 Dec 2005
I'm trying to execute the following query in SQL Query Analyzer:
select shipname,sum(total)from Orders where bogus='No'
and year(Date)='2004' and orderID like 'MN%'
Group by shipname
order by shipName
It gives the following error:
Server: Msg 409, Level 16, State 2, Line 1
The sum or average aggregate operation cannot take a varchar data type as an argument.
The data type of total is varchar, so how can I sum the total?
To total a value in a varchar column, you need to convert it to a type that can be totaled, eg: sum(cast(total as decimal(18,2)). However, if you've also got the possibility of invalid numeric varchar values, you'll need to check for that as well. That means something like: SUM(CASE WHEN ISNUMERIC(total) THEN CAST(total AS decimal(18,2)) ELSE 0 END)
Dig Deeper on SQL-Transact SQL (T-SQL)
Related Q&A from Greg Low
Find how to query in SQL Server to get all database names created by users.
Continue Reading
Triggers in SQL Server can be executed before a table is updated. Get triggers to read and extract table values before and after the table is updated.
Continue Reading
Find out why problems calling an extended stored procedure in SQL Server 2005 can involve security settings.
Continue Reading