2017-06-27 110 views
1

我試圖計算可通過不同渠道聯繫的客戶。下面的代碼會給我一個只有通過短信可聯繫的客戶的統計。SQL:計算列x如果列y = z

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

編輯您的問題,並提供樣本數據和期望的結果。 –

+0

我懷疑你的解決方案將沿着HAVING的線而不是WHERE。 –

回答

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; 
+0

我認爲'channel'是OP想要生成的一個「合成」字段。我認爲他正在尋找一個關鍵點,但我不知道紅移是否提供了一種方法。 – dasblinkenlight

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 

注:我不知道,如果亞馬遜的紅移有內置的樞紐設施。如果是這樣,你可能會有一個比這個窮人的支點實施更好的方法。

相關問題