SQL从多个表中选择最高列值

时间:2018-01-09 06:35:28

标签: sql greatest-n-per-group

我正在尝试仅在其他两个表中组合FirstName,LastName,VacationHours,SickLeaveHours和HireDate时查看RATE列中的最高值。

基本上,我只希望看到每位员工的当前税率,而不会看到他们之前的薪资历史记录。

SELECT HumanResources.EmployeePayHistory.EmployeeID
,HumanResources.EmployeePayHistory.RateChangeDate
,HumanResources.EmployeePayHistory.Rate
,HumanResources.EmployeePayHistory.PayFrequency
,HumanResources.EmployeePayHistory.ModifiedDate
,HumanResources.vEmployee.FirstName
,HumanResources.vEmployee.LastName
,HumanResources.Employee.VacationHours
,HumanResources.Employee.SickLeaveHours
,HumanResources.Employee.HireDate
FROM [AdventureWorks].[HumanResources].[EmployeePayHistory],
[AdventureWorks].[HumanResources].[vEmployee], 
[AdventureWorks].[HumanResources].[Employee]
WHERE HumanResources.EmployeePayHistory.EmployeeID = HumanResources.vEmployee.EmployeeID 
AND HumanResources.EmployeePayHistory.EmployeeID = HumanResources.Employee.EmployeeID[enter image description here][1]

1 个答案:

答案 0 :(得分:0)

您可以使用row_number()窗口功能为每个员工的费率变化编号,然后只需选择最后一个。

无论如何,值得一提的是,使用隐式连接(即from子句中的多个表)被视为不推荐使用的语法,您应该使用显式的join子句:

SELECT EmployeeID,
       RateChangeDate,
       Rate,
       PayFrequency,
       ModifiedDate,
       FirstName,
       LastName,
       VacationHours,
       SickLeaveHours,
       HireDate
FROM   (SELECT eph.EmployeeID,
               eph.RateChangeDate,
               eph.Rate,
               eph.PayFrequency,
               eph.ModifiedDate,
               ve.FirstName,
               ve.LastName,
               e.VacationHours,
               e.SickLeaveHours,
               e.HireDate,
               ROW_NUMBER() OVER (PARTITION BY eph.EmployeeID
                                  ORDER BY     eph.RateChangeDate DESC) AS rn
        FROM   AdventureWorks].[HumanResources].[EmployeePayHistory] eph
        JOIN   [AdventureWorks].[HumanResources].[vEmployee] ve ON 
               eph.EmployeeID = ve.EmployeeID
        JOIN   [AdventureWorks].[HumanResources].[Employee] e ON 
               eph.EmployeeID = e.EmployeeID) t
WHERE    rn = 1