我有一个员工数据库,员工出现了多次。
-
同一雇员的某些实例有员工部门,在其他情况下,员工部门缺少。为此,我需要与员工部门一起找到员工名称的不同。
-
一些员工根本没有任何员工部门。为此,我只需要找到不同的员工名称。
我的查询:
------for each unique employee, find department
--select columns
select
a.employee_name,b.employee_dept
from
--unique employee names
(
select
distinct employee_name
from
employeeDB
where
employee_name is not null and employee_name != ''
order by employee_name asc
) as a,
--employee name and employee dept sorted
(
select
employee_name,employee_dept
from
employeeDB
where employee_name is not null and employee_name != ''
order by employee_name asc, employee_dept desc
) as b
--condition for join
where
a.employee_name = b.employee_name
order by a.employee_name asc, b.employee_dept desc
limit 1000
我不确定为什么结果不会返回唯一的结果。我得到的结果类似于
Name Dept
A DepA
A DepB
A
B DepA
B
C DepZ
D
E
这将获得所有唯一名称(通过对其进行分组),并抓住(字母)最高的employee_dept
,可以找到每个
select employee_name, max(employee_dept) as dept
from employeeDB
where employee_name is not null and employee_name != ''
group by employee_name
order by employee_name asc
limit 1000