如何在单个查询中执行多个求和

时间:2017-04-03 09:31:28

标签: mysql

让我们说我有这张表:

表num1:

+----+-----+
| no | val |
+----+-----+
| 1  | 10  |
| 2  | 15  |
| 3  | 20  |
+----+-----+

表num2:

+----+-----+
| no | tot |
+----+-----+
| 1  | 15  |
| 2  | 20  |
| 3  | 25  |
+----+-----+

所以,我想在单个查询中选择表nu1.val和表num2.tot的总和值

 Select sum(a.val),sum(b.tot) from num1 a, num2 b

查询无效 请帮忙

4 个答案:

答案 0 :(得分:0)

select max(num1) ,max(num2) from (
  select sum(val) as num1,0 from num1
  union
  select 0,sum(tot) as num2 from num2) 

答案 1 :(得分:0)

在No column上加入这2个表然后加总。

select sum(n1.val),sum(n2.tot) from num1 n1 join num2 n2 on n1.no=n2.no

答案 2 :(得分:0)

选择Sum((从table_name中选择sum(col_name))+(从table_name中选择sum(col_name))); 经过测试: - Rahul Panwar

答案 3 :(得分:0)

感谢所有回复。但是,我已经弄明白了

从num1 n1 num2 n2中选择sum(distinct n1.val),sum(distinct n2.tot)