Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SUM two fields within an SQL query

Tags:

sql

ms-access

I need to get the total of two fields which are within the same row and input that number in a field at the end of that same row.

This is my code.

Sum(tbl1.fld1 + tbl1.fld2) AS [Total] 

Is this what the SUM function is used for, or can you only use the SUM function for getting the total of a column?

Thanks

like image 899
Anton Hughes Avatar asked Feb 14 '13 15:02

Anton Hughes


People also ask

Can you sum multiple columns in SQL?

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

How do you calculate two 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 you sum two rows in SQL?

SQL SUM() function Return the SUM of unique values. Expression made up of a single constant, variable, scalar function, or column name. The expression is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.

Can we add two columns in SQL?

You can add multiple columns to an SQL table using the ALTER TABLE syntax. To do so, specify multiple columns to add after the ADD keyword. Separate each column you want to add using a comma. Suppose that we want to add two columns called “salary” and “bio” to our existing “employees” table.


1 Answers

SUM is an aggregate function. It will calculate the total for each group. + is used for calculating two or more columns in a row.

Consider this example,

ID  VALUE1  VALUE2 =================== 1   1       2 1   2       2 2   3       4 2   4       5 

 

SELECT  ID, SUM(VALUE1), SUM(VALUE2) FROM    tableName GROUP   BY ID 

will result

ID, SUM(VALUE1), SUM(VALUE2) 1   3           4 2   7           9 

 

SELECT  ID, VALUE1 + VALUE2 FROM    TableName 

will result

ID, VALUE1 + VALUE2 1   3 1   4 2   7 2   9 

 

SELECT  ID, SUM(VALUE1 + VALUE2) FROM    tableName GROUP   BY ID 

will result

ID, SUM(VALUE1 + VALUE2) 1   7 2   16 
like image 186
John Woo Avatar answered Sep 22 '22 23:09

John Woo