简体   繁体   English

sql两个表的总和

[英]sql sum of sums of two tables

how to get a sum of two sums from two tables? 如何从两个表中得到两个总和?

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

doesn't work 不起作用

You are very close. 你很亲密 You just need parens around each subquery: 您只需要在每个子查询周围添加括号:

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

If either subquery could return NULL , you might prefer: 如果任何一个子查询都可以返回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;

Due to this link , you can do that by : 由于此链接 ,您可以通过以下方法实现:

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

also you can visit these links: 您也可以访问以下链接:

Query SUM for two fields in two different tables 查询两个不同表中两个字段的SUM

Getting the sum of several columns from two tables 从两个表中获取几列的总和

SQL: How to to SUM two values from different tables SQL:如何对不同表中的两个值求和

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

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

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