我有一個表的結構是這樣的:集體最大
employee
id int
manager_id int (the employee id of the manager)
name
...
awards
id int
employee_id int
points int (the award "value")
我怎樣才能找到其工作人員(那些誰直接向經理)的經理已經集體獎項最多的點?
我有一個表的結構是這樣的:集體最大
employee
id int
manager_id int (the employee id of the manager)
name
...
awards
id int
employee_id int
points int (the award "value")
我怎樣才能找到其工作人員(那些誰直接向經理)的經理已經集體獎項最多的點?
像這樣:
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
可能需要一些「GROUP BY」在那裏,使其正確,但這是一般的想法 –
哎呀!你的權利...現在修復。 – RBarryYoung
@Bohemian:想要戴帽子? ;-) – RBarryYoung
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
JOIN上employee.id = awards.employee_id,GROUP BY經理,做點SUM,ORDER BY點,並採取TOP 1,LIMIT 1或ROW_NUMBER <= 1(取決於數據庫) –
你可以舉一個數據的例子和你想要的結果嗎?你的問題是不明確的,因爲你沒有說你是否僅指直接的報告。 –
@GordonLinoff直接報告 - 這個問題已被編輯,以反映這 – Bohemian