I would like to extract the following information:
Customer_ids
that have been active on platform A and BCustomer_ids
that have been active on neither platform A and B (ie customers who have been active on any other platform other than A and B)Main table
date customer_id platform
2019-01-01 1 A
2019-01-01 1 B
2019-01-01 2 A
2019-01-01 2 B
2019-01-01 3 A
2019-01-01 4 A
2019-01-01 4 B
2019-01-01 5 C
2019-01-01 6 D
Output table 1
Date customerID_active_both_platforms
2019-01-01 1
2019-01-01 2
2019-01-01 4
Output table 2
Date customerID_active_neither_platforms
2019-01-01 5
2019-01-01 6
You may handle this using conditional aggregation. For the first requirement of customers with both platforms A and B:
SELECT
Date,
customer_id AS customerID_active_both_platforms
FROM yourTable
WHERE
platform IN ('A', 'B')
GROUP BY
Date,
customer_id
HAVING
MIN(platform) <> MAX(platform);
For the second requirement, customers having neither platform A nor B:
SELECT
Date,
customer_id AS customerID_active_neither_platforms
FROM yourTable
GROUP BY
Date,
customer_id
HAVING
COUNT(CASE WHEN platform IN ('A', 'B') THEN 1 END) = 0;
If you want this information per customer , then use two levels of aggregation -- first by customer/date and then by customer:
select date,
sum( is_a * is_b ) as num_ab,
sum( (1 - is_a) * (1 - is-b) ) as num_not_ab
from (select customer, date,
max(case when platform = 'A' then 1 else 0 end) as is_a,
max(case when platform = 'B' then 1 else 0 end) as is_b,
max(case when platform not in ('A', 'B') then 1 else 0 end) as is_not_ab
from t
group by customer, date
) t
from t
group by date;
Of course, you can filter with a where
clause to get customers that only meet one or the other condition.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.