【问题标题】:SQL for joining two tables and grouping by shared column用于连接两个表并按共享列分组的 SQL
【发布时间】:2021-07-09 15:01:09
【问题描述】:

我想加入两个表并使用它们共享的列来对结果进行分组,包括那些只出现在一个表中的 accountId 的空结果。

表一

AccountId productApurchases
Steve 1
Jane 5
Bill 10
Abed 2

表 b

AccountId productApurchases
Allan 1
Jane 10
Bill 2
Abed 1
Mike 2

期望的输出

AccountId productApurchases productBpurchases
Steve 1 0
Jane 5 10
Bill 10 2
Abed 2 1
Mike 0 2

我一直在尝试各种连接,但不知道如何按所有帐户 ID 进行分组。

非常感谢任何建议,谢谢。

【问题讨论】:

    标签: sql join group-by


    【解决方案1】:

    使用full join:

    select accountid,
           coalesce(productApurchases, 0) as productApurchases,
           coalesce(productBpurchases, 0) as productBpurchases
    from a full join
         b
         using (accountid);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      相关资源
      最近更新 更多