简体   繁体   English

sql查询从两个不同的表中获取两列的总和

[英]sql query to get sum of two columns from two different tables

I have two tables. 我有两张桌子。 I want to add all the values of one column from table 1 to all the values of a particular column of table 2. How to do that? 我想将表1中一列的所有值添加到表2中特定列的所有值。

for example 例如

table A 表A

Id Name  Salary 
1    A   20000 
2    B   30000

table B 表B

Id Name   Salary 
1    A    30000 
2    B    40000

I want the result as total salary= sum(salary of table A) + sum(salary of table B) 我想要的结果是total salary= sum(salary of table A) + sum(salary of table B)

Here result should come as 120000 结果应该是120000

Do this with a subquery: 使用子查询执行此操作:

select a.s + b.s
from (select sum(salary) as s from a) cross join
     (select sum(salary) as s from b);

Or, if one of the tables could be empty, union all would be better: 或者,如果其中一个表可以为空,则union all合并会更好:

select sum(salary)
from (select id, name, salary from a union all
      select id, name, salary from b
     ) ab;

Using a Union first. 首先使用联合。 Try this query: 试试这个查询:

select sum(salary) from 
(
select sum(Salary) as salary from tableA
union 
select sum(Salary) as salary from tableB
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM