Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find sum of multiple columns in a table in SQL Server 2005?

I have a table Emp which has these rows:

Emp_cd | Val1  | Val2  | Val3  | Total -------+-------+-------+-------+-------  1     | 1.23  | 2.23  | 3.43  |   2     | 23.03 | 12.23 | 2.92  |  3     | 7.23  | 9.05  | 13.43 |  4     | 03.21 | 78.23 | 9.43  | 

I want to find SUM of Val1, Val2, Val3 and which will show in the Total column.

like image 602
Tripati Subudhi Avatar asked Jun 14 '12 12:06

Tripati Subudhi


People also ask

How do I calculate multiple columns in SQL?

All you need to do is use the multiplication operator (*) between the two multiplicand columns ( price * quantity ) in a simple SELECT query. You can give this result an alias with the AS keyword; in our example, we gave the multiplication column an alias of total_price .

How do I sum all columns in a table in SQL?

The SQL AGGREGATE SUM() function returns the SUM of all selected column. Applies to all values. Return the SUM of unique values. Expression made up of a single constant, variable, scalar function, or column name.

Can you sum across columns in SQL?

We can use SUM() function on multiple columns of a table.


2 Answers

Easy:

SELECT     Val1,    Val2,    Val3,    (Val1 + Val2 + Val3) as 'Total' FROM Emp 

or if you just want one row:

SELECT     SUM(Val1) as 'Val1',    SUM(Val2) as 'Val2',    SUM(Val3) as 'Val3',    (SUM(Val1) + SUM(Val2) + SUM(Val3)) as 'Total' FROM Emp 
like image 141
aF. Avatar answered Sep 20 '22 16:09

aF.


You must also be aware of null records:

SELECT  (ISNULL(Val1,0) + ISNULL(Val2,0) + ISNULL(Val3,0)) as 'Total' FROM Emp 

Usage of ISNULL:

ISNULL(col_Name, replace value) 
like image 39
Salem Ahmed Avatar answered Sep 19 '22 16:09

Salem Ahmed