添加两个SUM函数的总和

时间:2014-09-25 18:50:51

标签: sql postgresql

如何使用postgresql对这些查询的结果进行求和?:

SELECT SUM(value) FROM credit_balance

SELECT SUM(value) FROM debit_balance

我试过这个,但它不起作用:

SELECT SUM(SELECT SUM(value) FROM credit_balance UNION ALL SELECT SUM(value) FROM debit_balance)

2 个答案:

答案 0 :(得分:3)

SELECT
  (SELECT SUM(value) FROM credit_balance) + (SELECT SUM(value) FROM debit_balance)

答案 1 :(得分:0)

总和后你缺少字段名称。您可以使用union all编写查询,如下所示:

select sum(val_sum) from (SELECT SUM(value) as val_sum FROM credit_balance UNION ALL SELECT SUM(value) as val_sum FROM debit_balance) as united_table;

OR

select sum(value) from (SELECT value FROM credit_balance UNION ALL SELECT value FROM debit_balance) as united_table.