SQL - 筛选两列

SQL - Filter on two columns

我试图在 sql 中获取两列的计数,每一列上都有一个 where 子句。

假设我的数据看起来像

person feature1   feature2
a       1           1
a       0           1
a       1           1
a       1           1
a       0           0
a       1           1
b       0           1
c       1           0

现在,我想按人对数据进行分组,分组后的数据应该如下所示

  person feature1   feature2
    a       2           1
    b       0           1
    c       1           0

我想计算每个人每列零的数量。我怎样才能通过 sql.

做到这一点

您可以使用条件聚合来执行此操作。 sum return 中的条件 1 或 0 取决于 true 或 false。

select person,sum(feature1=0),sum(feature2=0)
from tbl
group by person

在 Hive 中,您应该在求和之前将布尔值 returned 转换为 int

select person,sum(cast(feature1=0 as int)),sum(cast(feature2=0 as int))
from tbl
group by person

这里可以用case语句统计每个人的非零特征

select人, count(当 feature1>0 then 1 else null end 时的情况) F1, 计数(当 feature1>0 然后 1 else null end 时的情况)F2 从表 1 按人分组 ;