sql两个表之和的总和

时间:2017-10-29 12:31:36

标签: sql sum

如何从两张桌子中得到两笔钱的总和?

SELECT (SELECT SUM(col) FROM table1) + SELECT (SUM(col) from table2)    

不起作用

3 个答案:

答案 0 :(得分:0)

你非常接近。你只需要在每个子查询周围使用parens:

SELECT (SELECT SUM(col) FROM table1) + (SELECT SUM(col) from table2) 

如果任何子查询都可以返回NULL,您可能更喜欢:

SELECT COALESCE(t1.s, 0) + COALESCE(t2.s)
FROM (SELECT SUM(col) as s FROM table1) t1 CROSS JOIN
     (SELECT SUM(col) as s from table2) t2;

答案 1 :(得分:0)

由于这个link,您可以通过以下方式实现:

SELECT T1C1 , T2C1
FROM
 ( select SUM(Col1) T1C1 FROM  T1 ) A
CROSS JOIN 
 ( select SUM(Col1) T2C1 FROM  T2 ) B

您也可以访问以下链接:

Query SUM for two fields in two different tables

Getting the sum of several columns from two tables

SQL: How to to SUM two values from different tables

答案 2 :(得分:0)

select coalesce(sum(x),0) from
 (
    Select sum(a) x from tab1
    Union all
    Select sum(b) from tab2
 ) Ilv