一起添加两个计数(*)结果

时间:2017-03-13 19:29:23

标签: sql database postgresql select count

我有这两个查询,我想添加它们

SELECT count(*) FROM table2 GROUP BY table1_id
SELECT count(*) FROM table3 GROUP BY table1_id

我尝试了与this question中接受的答案类似的内容。区别在于我在两个查询中都有 group by 子句,我收到以下错误

  

错误:用作表达式

的子查询返回多行      

**********错误**********

我错过了什么?

3 个答案:

答案 0 :(得分:3)

您可以根据table1_id

加入这两个查询
SELECT a.table1_id, a.cnt + b.cnt
FROM   (SELECT   table1_id, COUNT(*) AS cnt
        FROM     table2 
        GROUP BY table1_id) a
JOIN   (SELECT   table1_id, COUNT(*) AS cnt
        FROM     table3 
        GROUP BY table1_id) b ON a.table1_id = b.table1_id

注意: 此查询隐式假定两个表具有相同的table1_id值。如果不是这种情况,则需要使用某种外连接。

答案 1 :(得分:1)

以下是如何添加2个表的计数:

WITH q1 AS (
    SELECT count(DISTINCT table1_id) as count from table2
), q2 AS (
    SELECT count(DISTINCT table1_id) as count from table3
)
SELECT (SUM(count + (SELECT count FROM q2)))
FROM q1

答案 2 :(得分:0)

您的子查询中有group by,但不显示这些组。这似乎很可疑。

你需要结合它们。第一个想法是FULL OUTER JOIN

SELECT COALESCE(t2.table1_id, t3.table1_id) as table1_id,
       t2.cnt, t3.cnt,
       (COALESCE(t2.cnt, 0) + COALESCE(t3.cnt, 0) ) as t23_cnt
FROM (SELECT table1_id, count(*) as cnt FROM table2 GROUP BY table1_id
     ) t2 FULL OUTER JOIN
     (SELECT table1_id, count(*) as cnt FROM table3 GROUP BY table1_id
     ) t3
     ON t2.table1_id = t3.table1_id;