Getting both Having and Not Having in same row
-
28-12-2020 - |
Question
I have a query which I get the customers that have more than 1 orders However, I would like to get the number of customer that has only 1 orders as well and divide them like 1 orders / more than 1 order
So that my table will have 3 colums
one_order, more_than_one_order, divided
I tried different approaches like duplicating the query like =1 but it is not the proper way
Query
SELECT COUNT(*)
FROM (
select customer_id from orders GROUP BY customer_id HAVING COUNT(order_id)>1
) A
Solution
You can use a case expression like:
SELECT count(case when cnt = 1 then 1 end) as one_order
, count(case when cnt > 1 then 1 end) as more_than_one_order
FROM (
select customer_id, count(1) as cnt from orders GROUP BY customer_id
) as T
You can also use a filter
clause for the count aggregates:
SELECT count(1) filter (where cnt = 1) as one_order
, count(1) filter (where cnt > 1) as more_than_one_order
FROM ...
For the third attribute you can either reuse the aggregates:
select count(1) filter (where cnt = 1) as ...
, count(1) filter (where cnt > 1) as ...
, count(1) filter (where cnt = 1) / count(1) filter (where cnt > 1) as ...
or add another level of nesting:
select one_order
, more_than_one_order
, one_order / more_than_one_order
from (
SELECT count(1) filter (where cnt = 1) as one_order
, count(1) filter (where cnt > 1) as more_than_one_order
FROM (
select customer_id, count(1) as cnt
from orders
GROUP BY customer_id
) as T1
) as T2
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange