最高工资的教师姓名 - 递归CTE

时间:2017-12-22 18:41:29

标签: sql sql-server

我正在尝试获得每个部门的最高工资,并以名字显示该教师作为单独的列。因此,部门1可能有4行,但一个名称显示最高工资。我使用SQL SERVER

With TeacherList AS(
Select Teachers.FirstName,Teachers.LastName,
Teachers.FacultyID,TeacherID, 1 AS LVL,PrincipalTeacherID AS ManagerID
FROM dbo.Teachers 
WHERE PrincipalTeacherID IS NULL

UNION ALL

Select Teachers.FirstName,Teachers.LastName,
Teachers.FacultyID,Teachers.TeacherID, TeacherList.LVL + 
1,Teachers.PrincipalTeacherID
FROM dbo.Teachers 
INNER JOIN TeacherList ON Teachers.PrincipalTeacherID = 
TeacherList.TeacherID
WHERE Teachers.PrincipalTeacherID IS NOT NULL)
SELECT * FROM TeacherList;

示例输出:

教师名字|老师姓氏|学院|教师薪酬最高

  Eric              Smith               1          Eric
  Alex              John                1          Eric
  Jessica           Sewel               1          Eric 
  Aaron             Gaye                2          Aaron
  Bob               Turf                2          Aaron

2 个答案:

答案 0 :(得分:0)

我不确定你的描述,但这将返回所有教师,最后一行是教师薪酬最高的老师的名字。

select tr.FirstName,
       tr.LastName,
       tr.FacultyID,
       th.FirstName
from Teachers tr
join (
  select FacultyID, max(pay) highest_pay
  from Teachers 
  group by FacultyID
) t on tr.FacultyID = t.FacultyID
join Teachers th on th.FacultyID = t.FacultyID and
                    th.pay = t.highest_pay

如果教职员工的薪水最高,则会产生意外结果(重复行)。在这种情况下,您可以使用窗口函数,如下所示:

select tr.FirstName,
       tr.LastName,
       tr.FacultyID,
       t.FirstName
from Teachers tr
join
(       
    select t.FirstName,
           t.FacultyID
    from 
    (
      select t.*, 
             row_number() over (partition by FacultyID order by pay desc) rn
      from Teachers t
    ) t
    where t.rn = 1
) t on tr.FacultyID = t.FacultyID

这将只显示一位来自薪水最高的教师的随机教师。

dbfiddle demo

答案 1 :(得分:0)

您可以使用echo OK

执行此操作
CROSS APPLY