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

问题描述

我需要为每个类别选择一个表中的所有群组,即使该类别在给定类别中缺失(并将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

有人知道如何实现这一目标吗?谢谢!

解决方法

您需要先交叉分类和分组,然后再进行左联接:

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