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

后端 未结 8 1973
爱一瞬间的悲伤
爱一瞬间的悲伤 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:48
    SELECT Emp_cd, Val1, Val2, Val3, SUM(Val1 + Val2 + Val3) AS TOTAL 
    FROM Emp
    GROUP BY Emp_cd, Val1, Val2, Val3
    
    0 讨论(0)
  • 2020-12-04 17:49

    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
    
    0 讨论(0)
  • 2020-12-04 17:52

    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)
    
    0 讨论(0)
  • 2020-12-04 17:53

    Another example using COALESCE. http://sqlmag.com/t-sql/coalesce-vs-isnull

    SELECT (COALESCE(SUM(val1),0) + COALESCE(SUM(val2), 0)
    + COALESCE(SUM(val3), 0) + COALESCE(SUM(val4), 0)) AS 'TOTAL'
    FROM Emp
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-04 17:56

    use a trigges it will work:-

    ->CREATE TRIGGER trigger_name BEFORE INSERT ON table_name

    FOR EACH ROW SET NEW.column_name3 = NEW.column_name1 + NEW.column_name2;

    this will only work only when you will insert a row in table not when you will be updating your table for such a pupose create another trigger of different name and use UPDATE on the place of INSERT in the above syntax

    0 讨论(0)
提交回复
热议问题