分组并包含 SQL 中的所有类别

Group and include all categories in SQL

我需要 select 每个类别的 table 中的所有组,即使给定类别缺少该组(并将 0 或 NULL 作为值) 我需要通过 SQL 查询 (Impala).

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

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

有人知道如何实现吗?谢谢!

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

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