我试图计算可通过不同渠道联系的客户。以下代码将仅提供可通过SMS联系的客户的统计数据。
with grouping as (
select distinct
case when sms_correct_flag = 'Y' then 'Y' else 'N' end as smsable,
case when email_correct_flag = 'Y' then 'Y' else 'N' end as emailable,
case when address_correct_flag = 'Y' then 'Y' else 'N' end as dmable,
contact_key
from raw.contacts
)
select count(distinct contact_key)
from grouping
where smsable = 'Y';
我希望最终找到一张包含频道'频道'作为专栏,'电子邮件','短信'' DM'作为行,并填写他们各自的客户数量。
这可能是一个计数(情况......)但是当我们检查一个与我们的列不同的列的情况时,无法弄清楚如何完成这项工作正在数。
任何帮助表示赞赏!
答案 0 :(得分:2)
由于您只有三个频道,因此您可以使用UNION ALL
来生成所需的结果:
with grouping as (
select
MAX(case when sms_correct_flag = 'Y' then 1 else 0 end) as smsable
, MAX(case when email_correct_flag = 'Y' then 1 else 0 end) as emailable
, MAX(case when address_correct_flag = 'Y' then 1 else 0 end) as dmable
, contact_key
from raw.contacts
group by contact_key
)
select 'sms' as channel, SUM(smsable) as cust_count from grouping
union all
select 'email' as channel, SUM(emailable) as cust_count from grouping
union all
select 'dm' as channel, SUM(dmable) as cust_count from grouping
注意:我不知道亚马逊的redshift是否内置了枢轴设施。如果确实如此,那么你可能有一个比这个穷人的支点实施更好的方法。
答案 1 :(得分:1)
这是你在找什么?
select channel,
sum(case when sms_correct_flag = 'Y' then 1 else 0 end) as smsable,
sum(case when email_correct_flag = 'Y' then 1 else 0 end) as emailable,
sum(case when address_correct_flag = 'Y' then 1 else 0 end) as dmable
from raw.contacts
group by channel;