如何为具有特定值的重复ID选择唯一ID计数

问题描述

例如,如果我有这张桌子

 report_date     id    customerCount    orderNr
  2020-02-20    123        12              10
  2020-02-19    123        18              11
  2020-02-18    123        0               12
  2020-02-20    321        0               0
  2020-02-19    321        0               0
  2020-02-18    321        0               0
  2020-02-20    456        17              13
  2020-02-19    456        0               0
  2020-02-18    456        15              14
  2020-02-20    654        0               0
  2020-02-19    654        0               0
  2020-02-18    654        0               0

我要选择其所有行均为customerCount = 0和orderNr = 0的id的计数

解决方法

要列出所有id,可以使用聚合和having。布尔聚合很容易表达约束:

select id
from mytable
group by id
having bool_and(customerCount = 0) and bool_and(order_nr = 0)

如果要计算满足条件的id个,可以添加另一级别的聚合:

select count(*) cnt
from (
    select id
    from mytable
    group by id
    having bool_and(customerCount = 0) and bool_and(order_nr = 0)
) t
,

一种方法使用两种聚合级别:

select count(*)
from (select id
      from t
      group by id
      having max(customerCount) = 0 and max(orderNr) = 0
     ) i;

注意:这是假设这些值永远不会为负,考虑到示例值和命名,这似乎很合理。

另一种方法使用not exists

select count(distinct id)
from t
where not exists (select 1
                  from t t2
                  where t2.id = t.id and
                        (t2.customerCount <> 0 or t.orderNr <> 0)
                 );
,
select count(table.id)
from table 
where customerCount = 0 and orderNr = 0
group by table.id