2016-03-14 126 views
0

這是我的查詢,但導致虛假其中編號行不同的,這就是說,只要TABLEA選擇2行和tableB的選擇3結果是假如何總結兩列在不同的表中兩個日期之間

select sum(tableA.value)+sum(tableB.value1)) 
from tableA,tableB 
where tableA.data between '2016-01-21' and '2016-03-09' 
and tableB.date2 between '2016-01-21' and '2016-03-09' 

回答

1

您需要在加入之前在子查詢中完成總和。一個簡單的規則:從不在from子句中使用逗號。

select coalesce(avalue, 0) + coalesce(bvalue, 0) 
from (select sum(a.value) as avalue 
     from tableA a 
     where a.data between '2016-01-21' and '2016-03-09' 
    ) a cross join 
    (select sum(b.value) as bvalue 
     from tableB b 
     where b.data between '2016-01-21' and '2016-03-09' 
    ) b; 
+0

但錯誤(關鍵字附近有語法錯誤「交叉」)......蔭使用SQL Server 2012 – SAMAN

+0

子查詢必須有別名 –

+0

@IvanStarostin。 。 。是的,他們當然應該有別名。 –

0

好的。所以這就是我的理解。 您正試圖總結兩個不同表格的兩列,並獲得總結列的總和。不是??糾正我,如果我錯了。如果是這樣的話

一個簡單的子查詢可以來你的救援。

Select 
    (Select SUM(value) From tableA 
      where data between '2016-01-21' and '2016-03-09') + 
    (Select SUM(value1) From tableB 
      where date2 between '2016-01-21' and '2016-03-09') FinalValue 
相關問題