2017-03-28 92 views
0

我有两个表分组通过聚合计算

表1:

Unsub|Email|UnsubValue 
Y | a | 100 
Y | b | 200 
N | c | NULL 
N | d | NULL 

表2:

Email|UnsubValue 
a |150 
a |200 
b |100 
b |150 
c |300 

我要计数具有0或不同的电子邮件的数量1+发生在表2中,其中表2中的未分配值是小于表1中的未分配值。

然后,我想通过表1中的unSub列进行分组。因此,所需的输出是这样的:

Unsub| Num Unsub | Count Distinct Email 
Y | 0 Unsub | 1 (refers to email a, which has no unsub occurances) 
Y | 1+ Unsub | 1 (refers to email b, which has 2 unsub occurances) 
N | 0 Unsub | 2 (refers to email c & d, which have no unsub occurances that meet the conditions) 
N | 1+ Unsub | 0 

回答

0

首先我创建了一个CTE一切可能的报告斗:

;with bucket_cte (Unsub, Id, UnsubBucket) 
as 
(select * 
from (select 'Y' as Unsub 
     union all 
     select 'N') Unsubs 
     cross join (
      select 0 AS Id, '0 Unsub' UnsubBucket 
      union all 
      select 1, '1+ Unsub' 
     ) as u 
) 


-- below the inner most sql just gets all the data that matches your WHERE requirment. 
-- the next sql up from that counts the distinct emails by Unsub values 
-- then we left join that to our report buckets 

select * 
from bucket_cte 
left join (
select data.Unsub, case when [Count] > 0 then 1 else 0 end as Id, Count(1) as EmailCount 
from (
    select a.Unsub, a.Email, count(1) [Count] 
    from a 
    left join b 
    on b.Email = a.Email 
    and b.UnsubValue < a.UnsubValue 
    group by a.Unsub, a.Email) as data 
group by data.Unsub, case when [Count] > 0 then 1 else 0 end) as reportData 
on bucket_cte.Unsub = reportData.Unsub 
and bucket_cte.Id = reportData.Id 
相关问题