0

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

Greens
  • 11
  • 3

3 Answers3

0

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:

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;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • @Greens . . . I don't think you will get a syntax error on either of these. In your query, I do explain it: "You just need parens around each subquery". – Gordon Linoff Oct 29 '17 at 20:48
0

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

Getting the sum of several columns from two tables

SQL: How to to SUM two values from different tables

Community
  • 1
  • 1
Fatemeh Abdollahei
  • 3,040
  • 1
  • 20
  • 25
  • 1
    @Greens - Because in second `select` you have placed the parenthesis in wrong place. `..+ SELECT (SUM(col)..` **-->** `..+ (SELECT SUM(col)..` – Pரதீப் Oct 29 '17 at 12:57
0
select coalesce(sum(x),0) from
 (
    Select sum(a) x from tab1
    Union all
    Select sum(b) from tab2
 ) Ilv 
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
Ab Bennett
  • 1,391
  • 17
  • 24