如何在SQL Server 2005中查找表中多列的总和?

时间:2012-06-14 12:46:20

标签: sql sql-server sql-server-2005

我有一个表Emp,其中包含以下行:

Emp_cd | Val1  | Val2  | Val3  | Total
-------+-------+-------+-------+-------
 1     | 1.23  | 2.23  | 3.43  | 
 2     | 23.03 | 12.23 | 2.92  |
 3     | 7.23  | 9.05  | 13.43 |
 4     | 03.21 | 78.23 | 9.43  |

我想找到SUM的{​​{1}},并在Val1, Val2, Val3列中显示。

9 个答案:

答案 0 :(得分:93)

易:

SELECT 
   Val1,
   Val2,
   Val3,
   (Val1 + Val2 + Val3) as 'Total'
FROM Emp

或者如果你只想要一行:

SELECT 
   SUM(Val1) as 'Val1',
   SUM(Val2) as 'Val2',
   SUM(Val3) as 'Val3',
   (SUM(Val1) + SUM(Val2) + SUM(Val3)) as 'Total'
FROM Emp

答案 1 :(得分:35)

您还必须了解null条记录:

SELECT  (ISNULL(Val1,0) + ISNULL(Val2,0) + ISNULL(Val3,0)) as 'Total'
FROM Emp

ISNULL的用法:

ISNULL(col_Name, replace value)

答案 2 :(得分:21)

正如常规SELECT

SELECT 
   Val1, Val2, Val3,
   Total = Val1 + Val2 + Val3
FROM dbo.Emp

或者您想确定总数并使用这些值更新表吗?

UPDATE dbo.Emp
SET Total = Val1 + Val2 + Val3

如果您希望此总数始终保持最新状态 - 您的表格中应该有一个计算列:

ALTER TABLE dbo.Emp
ADD CurrentTotal AS Val1 + Val2 + Val3 PERSISTED

然后你将始终获得当前总数 - 即使值发生变化:

SELECT 
   Val1, Val2, Val3, CurrentTotal
FROM dbo.Emp

答案 3 :(得分:3)

试试这个:

select sum(num_tax_amount+num_total_amount) from table_name;

答案 4 :(得分:0)

另一个使用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

答案 5 :(得分:0)

您好您可以使用简单的查询

select emp_cd, val1, val2, val3,
(val1+val2+val3) as total 
from emp;

如果您需要插入新行,

insert into emp select emp_cd, val1, val2, val3,
(val1+val2+val3) as total 
from emp;

为了更新,

update emp set total = val1+val2+val3;

这将更新所有列

答案 6 :(得分:0)

需要对具有空值的 Postgres db 表做类似的工作。最终创建了一个函数,因为要添加的 COALESCE 太多了。

CREATE OR REPLACE FUNCTION array_sum_float(float[])
    RETURNS float
AS
$$
DECLARE
    arrInts ALIAS FOR $1;
    sum int DEFAULT 0;
BEGIN
    FOR I IN ARRAY_LOWER(arrInts, 1)..ARRAY_UPPER(arrInts, 1)
        LOOP
            sum = sum + COALESCE(arrInts[I], 0);
        END LOOP;
    RETURN sum;
END;
$$
    LANGUAGE plpgsql;

SELECT array_sum_float(ARRAY [6,8, null, 2]);
SELECT array_sum_float(ARRAY [Val1, Val2, Val3]) from Emp;

答案 7 :(得分:-1)

使用它会起作用的触发: -

- > CREATE TRIGGER trigger_name BEFORE INSERT ON table_name

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

只有当您在表格中插入行时才会有效,而不是在您为这样的情况更新表格时 创建另一个不同名称的触发器,并在上面的语法中使用更新 更新

答案 8 :(得分:-2)

SELECT Emp_cd, Val1, Val2, Val3, SUM(Val1 + Val2 + Val3) AS TOTAL 
FROM Emp
GROUP BY Emp_cd, Val1, Val2, Val3