【问题标题】:Group and include all categories in SQL在 SQL 中分组并包含所有类别
【发布时间】:2021-01-14 07:57:31
【问题描述】:

我需要为每个类别选择表中的所有组,即使给定类别缺少该组(并将 0 或 NULL 作为值) 我需要通过 SQL 查询 (Impala) 来执行此操作。

下面报告一个例子(基本上我还需要动态显示第二个表的最后一行)。

Category     Group     Amount              Category     Group     Amount
+--------------------------------+          +--------------------------------+
   A           X          1                    A           X          1
   A           Y          2                    A           Y          2
   A           Z          5           ->       A           Z          5
   B           X          2                    B           X          2
   B           Y          3                    B           Y          3
                                               B           Z          0

有谁知道如何做到这一点?谢谢!

【问题讨论】:

    标签: sql join data-manipulation impala


    【解决方案1】:

    您需要先对类别和组进行交叉连接,然后再进行左连接:

    select c.category, g.group, coalesce(amount, 0)
    from
     ( -- all categories
       select distinct Category from tab
     ) as c
    cross join -- create all possible combinations
     ( -- all groups
       select distinct group from tab
     ) as g
    left join tab as a -- now join back the amount
      on c.category = a.category
     and g.group = a.Group
    

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 2019-09-06
      • 2023-03-14
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多