按汇总计算分组

时间:2017-03-28 00:30:13

标签: sql

我有两张桌子

表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

我想计算表2中出现0或1次出现次数的不同电子邮件的数量,其中表2中的unsub值小于表1中的unsub值。

然后,我想通过表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

1 个答案:

答案 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