Click here to Skip to main content
16,019,876 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to do sum of different columns data

What I have tried:

select (column1+column2+column3) as 'column4'
but in this case i am not getting proper o/P.
for eg:column1 data=7.8
column2 data=7.0
column3 data= 8.9
ten o/P is coming like 7.8.7.9.8.9
Posted
Updated 22-Aug-16 19:43pm
Comments
phil.o 22-Aug-16 4:58am    
Which datatype(s) are column1, column2 and column3?
Member 12363094 22-Aug-16 5:09am    
ooh that is varchar type

Looks like you have a problem with your DB: those values are stored as string based data (VARCHAR or NVARCHAR) instead of numeric fields. As a result, the strings are added as strings instead of as numbers.

While you could use CONVERT on each of the columns, it's a kludge round a serious problem. Change your DB: always store values in the most appropriate form: INT or FLOAT for numbers, DATE or DATETIME for dates, and only string based data goes in NVARCHAR or VARCHAR columns. If you don't this isn't the only problem it's going to give you...
 
Share this answer
 
Since your operands are strings, the + (String Concatenation) (Transact-SQL)[^] operator is used.
You have to convert the operands to numbers in order to use the arithmetic + (Add) (Transact-SQL)[^] operator.
See CAST and CONVERT (Transact-SQL)[^].


BTW: using numerical data types (instead of varchars) for holding numbers looks more natural to me.
 
Share this answer
 
v2
Comments
Member 12363094 22-Aug-16 5:32am    
then i have to convert varchar to float?
CPallini 22-Aug-16 5:38am    
Yes, or decimal, depending on your needs.
Refer Solution 1 and 2 for explanation

SQL
select  (CAST( column1 as float) + CAST( column2 as float)+ CAST( column3 as float)) as 'column4' from YourTable
 
Share this answer
 
SQL
SELECT 
   column1,
   column2,
   column3,
   (column1 + column2 + column3) as 'column4'
FROM table
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900