Reputation: 57
for example if i have this 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
i want to select the count of id that all of its rows are customerCount = 0 and orderNr = 0
Upvotes: 1
Views: 221
Reputation: 61
select count(table.id)
from table
where customerCount = 0 and orderNr = 0
group by table.id
Upvotes: 0
Reputation: 1270421
One method uses two levels of aggregation:
select count(*)
from (select id
from t
group by id
having max(customerCount) = 0 and max(orderNr) = 0
) i;
Note: This assumes that the values are never negative, which seems quite reasonable given the example values and naming.
Another method uses 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)
);
Upvotes: 1
Reputation: 222582
To list all the id
s, you can use aggregation and having
. Boolean aggregation comes handy to express the constraints:
select id
from mytable
group by id
having bool_and(customerCount = 0) and bool_and(order_nr = 0)
If you want to count how many id
s satisfy the conditions, you can add another level of aggregation:
select count(*) cnt
from (
select id
from mytable
group by id
having bool_and(customerCount = 0) and bool_and(order_nr = 0)
) t
Upvotes: 1