2012-09-25 91 views
1

我的大脑正在变成木薯,试图找出这个问题。我有一张下属和主管的表格。每个员工都有一些课程。这是一个例子。在MySQL中对结果进行分组

我有三个领域: 雇员标识,名称,supervisor_id

弗雷德·威尔基是一个主管和他的纪录是....

employee_id: 1 
name: Fred Wilkie 
supervisor_id: NULL 

特德·威尔基是一个卑微的工人和弗雷德是他的老板。他入境看起来是这样的....

employee_id: 2 
name: Ted Wilkie 
supervisor_id: 1 

我想什么我查询的样子是EMPLOYEE_ID,姓名和supervisor_id但supervisor_id应该等于EMPLOYEE_ID如果supervisor_id为NULL。

这有点儿工程...(我想我只是需要以某种方式改进它)

select employee_id, name, supervisor_id case when supervisor_id is NULL then employee_id else supervisor_id end from employees order by supervisor_id; 

问题的是,它下令所有记录第一,其中EMPLOYEE_ID等于supervisor_id,然后它只是吐出了那剩下的下属....

employee_id, name, supervisor_id 
1, Fred Wilkie, 1 
4, Gail Winston, 4 
2, Ted Wilkie, 1 
3, Lisa Wilkie, 1 
5, Russ Cablas, 4 
6, Ben Reynolds, 4 
etc, etc, etc... 

我想,这是什么......

employee_id, name, supervisor_id 
1, Fred Wilkie, 1 
2, Ted Wilkie, 1 
3, Lisa Wilkie, 1 
4, Gail Winston, 4 
5, Russ Cablas, 4 
6, Ben Reynolds, 4 
etc, etc, etc... 

在上面的例子中,我列出了第一个主管(Fred)(employee_id = supervisor_id),然后是他的所有下属。之后是盖尔,还有她的所有下属,等等。我认为我的团队很弱。

我们经营一家大公司(250名员工),所以我们想要一种方法将其保留在MySQL逻辑中。有人有想法吗?

非常感谢! 珍妮

回答

0
select employee_id, name, supervisor_id case when supervisor_id is NULL then employee_id else supervisor_id end from employees order by supervisor_id ASC; 

应该做的伎俩......

0

我认为你缺少的序列,让你在使用order by记录,但不庞廷序列ASCDESC

select employee_id, name, 
supervisor_id case when supervisor_id is NULL 
then employee_id else supervisor_id end 
from employees 
order by supervisor_id 
ASC; 

希望这项工作

1

最简单的解决方案是使用COALESCE

SELECT employee_ID, 
     name, 
     COALESCE(supervisor_id, employee_id) AS supervisor_id 
FROM employees 
ORDER BY supervisor_id, employee_ID 

SQLFiddle Demo

附加查询

SELECT a.employee_ID, 
     a.name, 
     COALESCE(b.name, a.name) AS Supervisor_Name 
FROM employees a 
     LEFT JOIN employees b 
      ON a.supervisor_ID = b.employee_ID 
ORDER BY COALESCE(b.supervisor_id, a.employee_id), employee_ID 

SQLFiddle Demo

(如果你想获得的,而不是ID他们的主管名字