繁体   English   中英

在SQL的两个列上计数不相同

[英]Count distinct on TWO columns on SQL

让我们考虑这个例子:

Employee     Function   Start_dept   End_dept
A               dev          10        13
A               dev          11        12
A               test          9         9
A               dev          13        11

我要选择的是员工,他们的职能以及“开始”和“结束”部门中的不同部门。 它将得到以下结果:

Employee     Function  count_distinct_dept
A                 dev          4
A                 test         1            `

对于开发人员A,我们只有4个不同的部门(10、11、12和13),因为我们不应该在2列(开始和结束)中计算重复的值。

我怎样才能做到这一点 ? (我正在使用mySQL)。 是否可以在没有任何JOIN或UNION的情况下按一个请求执行此操作? 还是必须使用其中之一? 由于我使用的是庞大的数据库(超过30亿行),因此我不确定联接或联合请求是否是最佳选择...

使用union all和聚合:

select Employee, Function, count(distinct dept)
from ((select Employee, Function, Start_dept as dept
       from e
      ) union all
      (select  Employee, Function, End_dept
       from e
      )
     ) e
group by Employee, Function;

如果要提高性能,建议从(Employee, Function, Start_Dept)(Employee, Function, End_Dept)上的两个索引开始。 然后:

select Employee, Function, count(distinct dept)
from ((select distinct Employee, Function, Start_dept as dept
       from e
      ) union all
      (select distinct Employee, Function, End_dept
       from e
      )
     ) e
group by Employee, Function;

子查询应扫描索引而不是整个表。 您仍然需要做最后的GROUP BY 我猜想在子查询中, COUNT(DISTINCT)UNION更好,但是您可以测试一下。

暂无
暂无

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

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