我正在尝试从下表中查找收到 1/2/3 封电子邮件的唯一客户的数量:
客户 ID | 月 | 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 |
这是所需的输出,在汇总每月的电子邮件数量后,计算收到 x 封电子邮件的唯一客户的数量:
月 | cust_with_1email | cust_with_2email | cust_with_3email |
---|---|---|---|
202311 | 2 | 1 | 0 |
202310 | 2 | 0 | 0 |
202309 | 3 | 0 | 0 |
我尝试使用 CASE 函数但没有成功:
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
选择 电子邮件总和, COUNT(*) AS unique_customer_count 从 (选择 客户 ID, SUM(email_cnt) AS email_sum 来自客户电子邮件 按 cust_id 分组)AS sum_table WHERE email_sum IN (1, 2, 3) 按 email_sum 分组;