2012-09-25 136 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他們的主管名字