集体最大

时间:2013-01-03 00:10:27

标签: sql

我有一个像这样的表结构:

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

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

我如何才能找到其员工(直接向经理报告的人)获得最多奖励积分的经理?

2 个答案:

答案 0 :(得分: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 :(得分: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