Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unique customers who received 1, 2, or emails

I’m trying to find the count of unique customers who received 1/2/3 emails from the table below:

cust_id month email_cnt
1 202311 1
1 202311 1
1 202310 1
1 202310 0
1 202309 1
2 202311 0
2 202311 0
2 202310 0
2 202310 1
2 202309 1
3 202311 0
3 202311 1
3 202310 0
3 202310 0
3 202309 1

This is the desired output, after summing the # of emails per month, count the number of unique customers who received x number of emails:

month cust_with_1email cust_with_2email cust_with_3email
202311 2 1 0
202310 2 0 0
202309 3 0 0

I’m trying to use a CASE function without success:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT distinct month, 
SUM(case when email_cnt = 1 then email_cnt end) cust_with_1email, 
SUM(case when email_cnt = 2 then email_cnt end) cust_with_2email, 
SUM(case when email_cnt = 3 then email_cnt end) cust_with_3email
FROM mytable
GROUP BY month

>Solution :

i can’t still not reproduce your result.

But

WITH CTE as (SELECT
cust_id, month, SUM(email_cnt) email_cnt
FROM mytable
GROUP BY cust_id, month)
SELECT month, 
SUM(case when email_cnt = 1 then email_cnt ELSE 0 end) cust_with_1email, 
SUM(case when email_cnt = 2 then email_cnt ELSE 0  end) cust_with_2email, 
SUM(case when email_cnt = 3 then email_cnt ELSE 0  end) cust_with_3email
FROM CTE
GROUP BY month
month cust_with_1email cust_with_2email cust_with_3email
202311 1 2 0
202310 2 0 0
202309 3 0 0

Will give you at least a deterministic result

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading