繁体   English   中英

SQL提取的简单分组依据

[英]Simple group-by for SQL pull

我有下表:

Check | Email | Count
Y     | a     |  1
Y     | a     |  1
Y     | b     |  1
N     | c     |  1
N     | d     |  1

我想按“检查”和每封电子邮件下的计数数对其进行分组。 像这样:

Check | Count #   | Email Addresses
Y     | 1 count   | 1 (refers to email b)
Y     | 2+ counts | 1 (refers to email a)
N     | 1 count   | 2 (refers to email c & d)
N     | 2+ counts | 0 (no emails meet this condition)

每个“检查”值都是特定于电子邮件的

最简单的方法是将值放在而不是行中

但是它需要两个聚合级别:

select check, sum(case when cnt = 1 then 1 else 0 end) as cnt_1,
       sum(case when cnt >= 2 then 1 else 0 end) as cnt_2plus
from (select check, email, count(*) as cnt
      from t
      group by check, email
     ) ce
group by check;

这应该可行,但是可能会有更干净的方法到达那里。 我认为,假设您在源表中有一封电子邮件为空的记录,那么您需要一个额外的聚合层来处理没有电子邮件满足条件的情况。 如果源表中没有这些案例的记录,则此方法将无效。

select check
      ,count_num
      ,case when email_addresses is null then 0 else email_addresses end as email_addresses
from (
select check, 
       case when count_sum = 1 then 1 when count_sum > 1 then 2+ else 0 end as count_num,
       count(distinct(email)) as email_addresses
group by check, count_num
from (
select check, sum(count) as count_sum, email
from table
group by check, email
)
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM