不使用内部查询,通过分组从两个不同的表计算计数和总和

时间:2018-10-29 05:06:11

标签: sql postgresql

我有两个表A分别为column id,phone_number,refer_amount

第二个B具有列phone_number,transaction_amount

现在我希望使用电话号码逐个分组而不使用内部查询的方式从两个表中获得refer_amount和transaction_amount的sum()和phone_number的count(),而不使用内部查询

表A

phone_number    refer_amount
123             50
456             80
789             90
123             90
123             80
123             20
456             20
456             79
456             49
123             49

表B

phone_number     transaction_amount
123              50
123              51
123              79
456              22
456              11
456              78
456              66
456              88
456              88
456              66
789              66
789              23
789              78
789              46

我尝试了以下查询,但它给了我错误的输出:

SELECT a.phone_number,COUNT(a.phone_number) AS refer_count,SUM(a.refer_amount) AS refer_amount,b.phone_number,COUNT(b.phone_number) AS toal_count,SUM(b.transaction_amount) AS transaction_amount FROM dbo.A AS a,dbo.B AS b WHERE a.phone_number=b.phone_number GROUP BY a.phone_number,b.phone_number

输出(错误):

phone_number  refer_count  refer_amount  phone_number  transaction_count  transaction_amount
123           15           867           123           15                 900
456           28           1596          456           28                 1676
789           5            450           789           5                  291

输出(我想要的):

phone_number  refer_count  refer_amount  phone_number  transaction_count  transaction_amount
123           5            289           123           3                  180
456           4            228           456           7                  419
789           1            90            789           5                  291

2 个答案:

答案 0 :(得分:1)

我将在单独的子查询中对B表进行聚合,然后加入该表:

SELECT
    a.phone_number,
    COUNT(a.phone_number) AS a_cnt,
    SUM(a.refer_amount)   AS a_sum,
    COALESCE(b.b_cnt, 0)  AS b_cnt,
    COALESCE(b.b_sum, 0)  AS b_sum
FROM A a
LEFT JOIN
(
    SELECT
        phone_number,
        COUNT(*) AS b_cnt,
        SUM(transaction_amount) AS b_sum
    FROM B
    GROUP BY phone_number
) b
    ON a.phone_number = b.phone_number;

当前方法的一个主要潜在问题是联接可能导致重复计数,因为phone_number表中的给定A记录由于联接而被复制。

说到连接,请注意,上面我使用了显式连接,而不是您使用的隐式连接。通常,您不应在FROM子句中添加逗号。

答案 1 :(得分:0)

这可以帮助您。在检查a.phone_number = b.phone_number时,您不需要sum(b.phone_number)。电话号码需要不同,因为要考虑两列。

对于分组依据,不在聚合函数中的任何内容都必须按函数分组。

select a.phone_number, count(distinct a.phone_number), sum(a.refer_amount),
  sum (b.transaction_amount) 
  from A as a, B as b 
where a.phone_number=b.phone_number 
group by a.phone_number