如何 select 具有特定值的重复 ID 的唯一 ID 计数
how to select the unique id count for repeated id that have a specific value
例如,如果我有这个 table
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
我想select id 的计数,它的所有行都是 customerCount = 0 和 orderNr = 0
要列出所有 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
例如,如果我有这个 table
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
我想select id 的计数,它的所有行都是 customerCount = 0 和 orderNr = 0
要列出所有 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