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

后端 未结 8 1983
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 17:13

I have a table Emp which has these rows:

Emp_cd | Val1  | Val2  | Val3  | Total
-------+-------+-------+-------+-------
 1     | 1.23  | 2.23  |         


        
8条回答
  •  天命终不由人
    2020-12-04 17:55

    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
    

提交回复
热议问题