2014-11-06 116 views
0

我有一個sql語句,它會給我兩個使用子查詢的表中的兩列。MS SQL Server sum字段的總和

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或爲了做到這一點等等。

有人能幫助嗎?

+0

您可以使用子查詢 – bksi 2014-11-06 00:48:49

回答

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 
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 
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

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