2013-01-03 41 views
2

我有一個表的結構是這樣的:集體最大

employee 
    id int 
    manager_id int (the employee id of the manager) 
    name 
    ... 

awards 
    id int 
    employee_id int 
    points int (the award "value") 

我怎樣才能找到其工作人員(那些誰直接向經理)的經理已經集體獎項最多的點?

+0

JOIN上employee.id = awards.employee_id,GROUP BY經理,做點SUM,ORDER BY點,並採取TOP 1,LIMIT 1或ROW_NUMBER <= 1(取決於數據庫) –

+0

你可以舉一個數據的例子和你想要的結果嗎?你的問題是不明確的,因爲你沒有說你是否僅指直接的報告。 –

+0

@GordonLinoff直接報告 - 這個問題已被編輯,以反映這 – Bohemian

回答

3

像這樣:

SELECT 
    mgr.id, 
    mgr.name, 
    SUM(awd.points) As TotalStaffPoints 
FROM employee As mgr 
JOIN employee As stf ON mgr.id = stf.manager_id 
JOIN awards As awd ON stf.id = awd.employee_id 
GROUP BY mgr.id, mgr.name 
ORDER BY TotalStaffPoints DESC 
+1

可能需要一些「GROUP BY」在那裏,使其正確,但這是一般的想法 –

+0

哎呀!你的權利...現在修復。 – RBarryYoung

+0

@Bohemian:想要戴帽子? ;-) – RBarryYoung

2
select top 1 employee.manager_id, SUM(awards.points) as total 
from employee 
join awards on employee.id = awards.employee_id 
group by employee.manager_id 
order by SUM(awards.points) desc