2017-04-08 165 views
0

我正在使用Adventureworks2012數據庫學習SQL。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

如果你希望所有但對僱員的第一份薪水,那麼你應該學習如何使用窗口功能。如果你正在學習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()