Sql 如何为具有特定值的重复id选择唯一id计数
例如,如果我有这张桌子Sql 如何为具有特定值的重复id选择唯一id计数,sql,postgresql,group-by,count,having-clause,Sql,Postgresql,Group By,Count,Having Clause,例如,如果我有这张桌子 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-
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;
一种方法使用两级聚合:
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;
注意:这假设值从来都不是负值,考虑到示例值和命名,这似乎很合理
另一种方法不存在: