How to SUM two fields within an SQL query
Solution 1:
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
Solution 2:
Try the following:
SELECT *, (FieldA + FieldB) AS Sum
FROM Table
Solution 3:
Just a reminder on adding columns. If one of the values is NULL the total of those columns becomes NULL. Thus why some posters have recommended coalesce with the second parameter being 0
I know this was an older posting but wanted to add this for completeness.
Solution 4:
ID VALUE1 VALUE2
===================
1 1 2
1 2 2
2 3 4
2 4 5
select ID, (coalesce(VALUE1 ,0) + coalesce(VALUE2 ,0) as Total from TableName
Solution 5:
SUM is used to sum the value in a column for multiple rows. You can just add your columns together:
select tblExportVertexCompliance.TotalDaysOnIncivek + tblExportVertexCompliance.IncivekDaysOtherSource AS [Total Days on Incivek]