SQL - 如何根据它们之间的ID加入两个表并对列进行SUM?

时间:2017-11-16 14:32:29

标签: mysql sql join sum

我有两张桌子。一个表是主数据

表tbl1:

+-------------+------------+------------+
| ID          | Name       | Total      | 
+-------------+------------+------------+
| 1           | a          | 10         |
| 2           | b          | 5          |
| 3           | c          | 4          |
| 4           | a          | 4          |
+-------------+------------+------------+

第二个表tbl2包含子数据。表之间的关键是ID

表tbl2:

+-------------+------------+
|id           | qty        | 
+-------------+------------+
| 1           | 4          |              
| 1           | 3          |                
| 1           | 1          |                
| 3           | 1          |                
| 3           | 3          |                
+-------------+------------+

我需要得到这样的输出:

输出:

+-------------+------------+------------+
| name        | sum_tot    | sum_qty    | 
+-------------+------------+------------+
| a           | 14         | 8          |
| b           | 5          | 0          |
| c           | 4          | 4          |
+-------------+------------+------------+

我曾试过这个:

select tbl1.name, SUM(tbl1.total), SUM(tbl2.qty)
from tbl1
left join tbl2 ON tbl1.id = tbl2.id
GROUP by tbl1.name

我得到的输出是:

输出:

+-------------+------------+------------+
| name        | sum_tot    | sum_qty    | 
+-------------+------------+------------+
| a           | 34         | 8          |
| b           | 5          |null        |
| c           | 8          | 4          |
+-------------+------------+------------+

哪个不正确。

以下是sql fiddle

enter image description here

第一张表格的摘要与第二张表格无关。似乎不知何故查询运行了三次。

3 个答案:

答案 0 :(得分:4)

您可以简单地使用相关的子查询来计算tbl2总和:<​​/ p>

select tbl1.name, 
       SUM(tbl1.total), 
       SUM(COALESCE((select SUM(tbl2.qty) 
                     from tbl2
                     where tbl1.id = tbl2.id), 0)) as qty_tot
from tbl1
GROUP by tbl1.name

答案 1 :(得分:3)

2

答案 2 :(得分:0)

select tbl1.name, SUM(tbl1.total), SUM(COALESCE(tbl2.qty, 0))
from tbl1
left join tbl2 ON tbl1.id = tbl2.id
GROUP by tbl1.name