MS SQL Server和字段的总和

时间:2014-11-06 00:47:11

标签: sql sql-server

我有一个sql语句,它会使用子查询从两个表中给我两列。

select 
    sum(field1) as f1_sum,
    (select sum(field2) from table2) as f2_sum
from
    table1
group by
    table1.field_x

我希望将f1_sum + f2_sum的总和作为此查询的第三列输出。看起来很简单,但我无法找到解决方法。问题是如何得到求和字段的总和。

我可以编写SP或视图来执行此操作等。

有人可以协助吗?

4 个答案:

答案 0 :(得分:1)

您可以使用子查询,如:

SELECT t1.f1_sum+t1.f2_sum AS total_sum FROM 
    (select sum(field1) as f1_sum , (select sum(field2) from table2) as f2_sum 
       from table1
     group by table1.field_x) AS t1

答案 1 :(得分:1)

我建议这样做:

select t1.f1_sum, t2.f2_sum, coalesce(t1.f1_sum, 0) + coalesce(t2.f2_sum, 0)
from (select sum(field1) as f1_sum
      from table1 t1
      group by t1.field_x
     ) t1 cross join
     (select sum(field2) as f2_sum from table2) t2;

如果可能,我更喜欢在from子句中保留表引用。我添加了coalesce(),以防任何值为NULL

答案 2 :(得分:0)

你也可以试试这个:

SELECT SUM(a.field1) f1_sum, 
       SUM(b.field2) f2_sum,
       (SUM(a.field1) + SUM(b.field2)) f3_sum
from table1 a, table2 b

答案 3 :(得分:0)

只需你可以写,

select sum(field1) as f1_sum
       , (select sum(field2) from table2) as f2_sum
       , (ISNULL(sum(field1),0) + ISNULL((select sum(field2) from table2),0)) AS Total_Sum
from table1
group by table1.field_x