左连接表与总和 - 导致问题

时间:2016-05-17 16:00:31

标签: sql sql-server

我正在尝试左连接多个表,其中两个和列都连接在中间步骤表上。

表格如下:

表1

ID  Value1
1   3
2   2
3   3

表2

ID  Value1
1   5
2   2
3   2
4   1

Jointable

ID
1
2
3
4
5
6

我正在尝试输出:

Table1Value1SUM Table2Value1Sum
8 | 10

使用SQL:

SELECT SUM(Table1.Value1) Table1Value1SUM,SUM(Table2.Value1) Table2Value1Sum From Table1
Left Join JoinTable
On JoinTable.ID = Table1.ID
Left Join Table2
On Table2.ID = Table1.ID

我得到了这些结果:

Table1Value1SUM Table2Value1Sum
8 | 9

3 个答案:

答案 0 :(得分:3)

jointable必须left join与其他2个表格一起使用。

SELECT SUM(Table1.Value1) Table1Value1SUM,SUM(Table2.Value1) Table2Value1Sum 
From JoinTable 
Left Join Table1 On JoinTable.ID = Table1.ID
Left Join Table2 On JoinTable.ID = Table2.ID

答案 1 :(得分:1)

Left Join Table2 JoinTable代替Table1

SELECT SUM(Table1.Value1) Table1Value1SUM,SUM(Table2.Value1) Table2Value1Sum From Table1
Left Join JoinTable
On JoinTable.ID = Table1.ID
Left Join Table2
On JoinTable.ID = Table2.ID

答案 2 :(得分:0)

有什么可以加入到此?你想要table1和table2的总和,因此:

select
  (select sum(value1) from table1) as table1sum,
  (select sum(value1) from table2) as table2sum

select t1.table1sum, t2.table2sum
from
  (select sum(value1) as table1sum from table1) t1
cross join
  (select sum(value1) as table2sum from table2) t2;