SQL语句帮助请求

时间:2017-04-08 14:30:54

标签: sql sql-server

我正在使用Adventureworks2012数据库学习SQL。

我正在尝试创建一个查询来查找所有有加薪的员工。 以下是我得到的结果的前6行:

第一列是businessentityid和加注日期。

BID Salary Raise Date
4   05.01.2002 00:00:00
4   01.07.2004 00:00:00
4   15.01.2006 00:00:00
16  20.01.2002 00:00:00
16  16.08.2003 00:00:00
16  01.06.2006 00:00:00

使用以下声明:

select  
    RateChangeDate, Rate, BusinessEntityID
from 
    HumanResources.EmployeePayHistory
where 
    BusinessEntityID in (select BusinessEntityID
                         from HumanResources.EmployeePayHistory
                         group by BusinessEntityID
                         having count (*) > 1);

现在我要做的是删除每个结果的第一行,因为这是该人被雇用而不是加薪的第一个薪水。

此表唯一的额外列是Rate,它显示每个日期的费率。

enter image description here

图片的费率栏已添加到上述声明中。

谢谢:)

1 个答案:

答案 0 :(得分:1)

如果你想要一个员工的第一份工资,那么你应该学习如何使用窗口功能。如果您正在学习SQL,我会建议您快速学习它们,因为它们非常强大且有用。

您可以使用ROW_NUMBER()执行所需操作:

select RateChangeDate, Rate, BusinessEntityID
from (select eph.*,
             row_number() over (partition by BusinessEntityID order by RateChangeDate desc) as seqnum
      from HumanResources.EmployeePayHistory eph
     ) eph
where seqnum > 1;

您可以在SQL Server文档中阅读row_number()