Posted by gurpreet, Nov. 16, 2021, 9:34 a.m.
SQL#177
I have solved this query but taking union of two results, one with 'both' category and other with individual ones.
But my answer is deviating a tiny bit, not sure which edge case I am missing. Apprecaite your inputs, thanks!
platform_category num_customers spend
both 30 185455.260000001
desktop_only 15 96647.469999999
mobile_only 5 33410.040000000
Query:
With multiplatform_customers as (
select customer_id, count(distinct channel) as cnt
from orders
group by customer_id
having count(distinct channel) >1
),
agg_multi as (
SELECT 'both' as platform_category,
count(distinct a.customer_id) as num_customers,
sum(qty*unit_price_usd) as spend
FROM orders a
INNER JOIN multiplatform_customers b
ON a.customer_id = b.customer_id
),
agg_individual as (
SELECT case when a.channel = 'desktop' then 'desktop_only'
else 'mobile_only' end as platform_category,
count(distinct customer_id) as num_customers,
sum(a.qty*a.unit_price_usd) as spend
FROM orders a
WHERE a.customer_id NOT IN (SELECT distinct customer_id from multiplatform_customers)
GROUP BY a.channel
)
SELECT * FROM agg_multi
UNION
SELECT * FROM agg_individual
But my answer is deviating a tiny bit, not sure which edge case I am missing. Apprecaite your inputs, thanks!
platform_category num_customers spend
both 30 185455.260000001
desktop_only 15 96647.469999999
mobile_only 5 33410.040000000
Query:
With multiplatform_customers as (
select customer_id, count(distinct channel) as cnt
from orders
group by customer_id
having count(distinct channel) >1
),
agg_multi as (
SELECT 'both' as platform_category,
count(distinct a.customer_id) as num_customers,
sum(qty*unit_price_usd) as spend
FROM orders a
INNER JOIN multiplatform_customers b
ON a.customer_id = b.customer_id
),
agg_individual as (
SELECT case when a.channel = 'desktop' then 'desktop_only'
else 'mobile_only' end as platform_category,
count(distinct customer_id) as num_customers,
sum(a.qty*a.unit_price_usd) as spend
FROM orders a
WHERE a.customer_id NOT IN (SELECT distinct customer_id from multiplatform_customers)
GROUP BY a.channel
)
SELECT * FROM agg_multi
UNION
SELECT * FROM agg_individual