在SQL中为每个公司和域分配最大计数公司

时间:2018-09-11 18:43:37

标签: sql sql-server max

enter image description here我正在尝试在图像中实现输出。

我可以获取Company,Domain和Domain_count,不确定如何添加最后一列来显示具有最大域数的公司名称

到目前为止:

SELECT company, 
       RIGHT(email, LEN(email) - CHARINDEX('@', email)) as Domain, 
       count(RIGHT(email, LEN(email) - CHARINDEX('@', email))) as Count_of_Domain 
  FROM table 
 where company <> '' 
   and email <> '' 
   and company <> 'NULL' 
 group 
    by company, 
       RIGHT(email, LEN(email) - CHARINDEX('@', email))

2 个答案:

答案 0 :(得分:1)

我想我会使用窗口函数来写这个:

select company, domain, count_of_domain,
       max(case when seqnum = 1 then company end) over (partition by domain) as company_with_max_domain
from (select t.company, v.Domain, count(*) as Count_of_Domain,
             row_number() over (partition by v.domain order by count(*) desc) as seqnum
      from table t cross apply
           (values (RIGHT(email, LEN(email) - CHARINDEX('@', email))) ) v(domain)
      where t.company <> '' and t.email <> '' and t.company <> 'NULL' 
      group by t.company, v.domain
     ) cd

答案 1 :(得分:0)

您可以使用子查询,在该子查询中,您仅选择按计数降序排列的第一行。如果您还使用CTE,则无需重复太多。

WITH cte
AS
(
SELECT company, 
       right(email, len(email) - charindex('@', email)) as domain, 
       count(right(email, len(email) - charindex('@', email))) as count_of_domain 
       FROM table 
       WHERE company <> '' 
             AND email <> '' 
             AND company <> 'NULL' 
       GROUP company, 
             right(email, len(email) - charindex('@', email))
)
SELECT company,
       domain,
       count_of_domain,
       (SELECT TOP 1
               company
               FROM cte
               ORDER BY count_of_domain DESC) company_with_max_domain_count
       FROM cte;

编辑:以上原始问题已得到回答。

如果您只想显示某个域的顶级公司,而不是全部显示顶级公司,请在子查询中过滤该域。

WITH cte
AS
(
SELECT company, 
       right(email, len(email) - charindex('@', email)) as domain, 
       count(right(email, len(email) - charindex('@', email))) as count_of_domain 
       FROM table 
       WHERE company <> '' 
             AND email <> '' 
             AND company <> 'NULL' 
       GROUP company, 
             right(email, len(email) - charindex('@', email))
)
SELECT c1.company,
       c1.domain,
       c1.count_of_domain,
       (SELECT TOP 1
               c2.company
               FROM cte c2
               WHERE c2.domain = c1.domain
               ORDER BY c2.count_of_domain DESC) company_with_max_domain_count
       FROM cte c1;