在配置单元中使用 group by 函数获取聚合计数,并在数据对输入中的类别不可用时获取零作为计数输出 table

Using group by function in hive to get aggregated counts and get zero as count output when the data is not available for a category in input table

我有一个输入 table,如下所示,我正在尝试获取聚合计数:

Bins/buckets 是固定的。这个例子有 buckets/bins - 1 到 90, 97,98。这些需要计数 buckets/bins。

每当输入 table 中有可用数据时,我都能获得所有 bin 的计数。但是当数据不可用时,它不会显示为零计数。

非常感谢此处的任何帮助。提前致谢。

示例:“97”值未出现在 year=2015 中。因此它在输出 table.

中应该有零计数

我试过的代码:

select 'ada' 作为属性,年,'98' 作为 bin,计数(年) 作为 bin_count 来自 mrmg_atrib_monit_psi_db.ada_data_types_negative 其中 ada = 98
按年分组联合所有 select 'ada' 作为属性,年,'97' 作为 bin,计数(年) 作为 bin_count 来自 mrmg_atrib_monit_psi_db.ada_data_types_negative 其中 ada = 97
按年分组联合所有 select 'ada' as attribute, year,'1 到 90' as bin,count(year) as bin_count from mrmg_atrib_monit_psi_db.ada_data_types_negative where ada BETWEEN 1 and 90 按年份分组

"pre-defined" 我假设你的意思是你有一个 table 的 bin 定义。然后,您可以使用 cross join 生成行并使用 left join 生成数据:

select y.year, b.bin, count(i.year) as cnt
from (select distinct year from input) y cross join
     bins b left join
     input i
     on i.year = y.year and i.ada between b.lo and b.hi
group by y.year, b.bin;

select 'ada' 作为属性,年,'98' 作为 bin,计数(年) 作为 bin_count 来自 mrmg_atrib_monit_psi_db.ada_data_types_negative 其中 ada = 98
按年分组联合所有 select 'ada' as attribute, year,'97' as bin, SUM(CASE WHEN ada = 97 THEN 1 ELSE 0 END) 作为 bin_count 来自 mrmg_atrib_monit_psi_db.ada_data_types_negative 其中 ada = 97
按年分组联合所有 select 'ada' as attribute, year,'1 到 90' as bin,count(year) as bin_count from mrmg_atrib_monit_psi_db.ada_data_types_negative where ada BETWEEN 1 and 90 按年份分组

解决方案:将 select 语句中末尾的 where 函数替换为 Sum(case) 也有助于获得零计数