2017-03-28 90 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 
相關問題