How to find sum of multiple columns in a table in SQL Server 2005?
Solution 1:
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
Solution 2:
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)
Solution 3:
Just as a regular SELECT
?
SELECT
Val1, Val2, Val3,
Total = Val1 + Val2 + Val3
FROM dbo.Emp
Or do you want to determine that total and update the table with those values?
UPDATE dbo.Emp
SET Total = Val1 + Val2 + Val3
If you want to have this total be current at all times - you should have a computed column in your table:
ALTER TABLE dbo.Emp
ADD CurrentTotal AS Val1 + Val2 + Val3 PERSISTED
Then you will always get the current total - even if the values change:
SELECT
Val1, Val2, Val3, CurrentTotal
FROM dbo.Emp