创建一个查询(来自不同表的总和)

时间:2019-05-27 14:21:04

标签: sql ms-access

我有3个表,我想对值求和:

Table 1  
id............value  
31001.........200  
31002.........100  
31003.........1  
31004.........0  
31005.........0  


Table 2  
id...........value  
31001.........1  
31002.........1  
31004.........5  

Table 3  
id...........value  
31001.........2  
31003.........2  
31005.........1

我尝试使用以下代码:

SELECT table1.id, Sum([table1].[Value]+[table2].[Value]+[table3].[Value])
FROM (table1 LEFT JOIN table2 ON table1.[id] = table2.[id]) LEFT JOIN table3 ON table1.[id] = table3.[id]
WHERE (((table2.id) Is not Null) and (table3.id) and (table2.id))
GROUP BY table1.id;

UNION

SELECT table1.id,Sum([table1].[Value]+[table2].[Value])
FROM table1 LEFT JOIN table2 ON table1.[id] = table2.[id]
WHERE (((table2.id) Is not Null))
GROUP BY table1.id;

UNION

SELECT table1.id,Sum([table1].[Value]+[table3].[Value])
FROM table1 LEFT JOIN table3 ON table1.[id] = table3.[id]
WHERE (((table3.id) Is not Null))
GROUP BY table1.id;

我想要这样的结果:

id.........value  
31001.......223  
31002.......111  
31003.........3  
31004.........5  
31005.........1

但是我得到了

id..........value  
31001.......221  
31001.......222  
31001.......223  
31002.......111  
31003.........3  
31004.........5  
31005.........1

我该如何解决?

1 个答案:

答案 0 :(得分:0)

首先对所有3个表使用value,然后对id列乘以select id, sum(value) as totalvalue from ( select id, value from table1 union all select id, value from table2 union all select id, value from table3 ) group by id order by id

id  totalvalue
31001   203
31002   101
31003   3
31004   5
31005   1

结果将是:

var first = ['1+2', '10+20', '100+200'];
var second = ['3', '30', '300'];

var index = Math.floor(Math.random()*first.length);
var first_value = first[index];
var second_value = second[index];

document.getElementById('first_value').innerHTML = first_value;
document.getElementById('second_value').innerHTML = second_value;