2011-02-14 60 views
0

我想弄清楚如何選擇一個表,其中的價值是最高薪酬的人的ID。Sql得到MAX的其他值

所以,如果我有

表= theJobs

JobID Pay 
---------- 
12345 10 
12346 12 
12347 13 

表= thePerson

Person JobID 
-------------- 
Person1 1 
Person2 2 
Person3 3 

表=出租(FKS)

JobID PersonID 
---------------- 
12345 2 
12347 1 
12346 3 

我想它顯示最大支付的人,所以它守ld顯示

Person1 

我試圖使用哪裏爲一個最大值功能,但它似乎失敗。我對這些小組功能非常厭煩。我想我更多地問如何使用組函數作爲約束而不是任何事情。因爲我以前有過類似的問題。

+1

什麼RDBMS您使用的? – 2011-02-14 01:37:08

回答

0

該解決方案將工作在幾乎所有的數據庫系統:

Select .... 
From thePerson As P 
    Join (
      Select H1.PersonId, Max(J1.Pay) As MaxPay 
      From hire As H1 
       Join theJobs As J1 
        On J1.JobId = H1.JobID 
      Group By H1.PersonId 
      ) As PayPerPerson 
     On PayPerPerson.PersonId = P.Person 
Where Exists (
       Select 1 
       From hire As H2 
        Join theJobs As J2 
         On J2.JobId = H2.JobID 
       Where H2.PersonId = P.Person 
       Having Max(J2.Pay) = PayPerPerson.MaxPay 
       ) 

如果您正在使用支持排名函數和公用表表達式(如SQL Server 2005和更高版本)的DBMS,則問題會更加容易。該解決方案將只顯示一個名字,而忽略關係:

With RankedPay As 
    (
    Select ... 
     , Row_Number() Over(Order By J.Pay Desc) As Rnk 
    From thePerson As P 
     Join hire As H 
      On H.PersonId = P.Person 
     Join theJobs As J 
      On J.JobId = H.JobId 
    ) 
Select ... 
From RankedPay 
Where Rnk = 1 

該解決方案將顯示任何匹配的最高支付,包括關係是:

With RankedPay As 
    (
    Select ... 
     , Rank() Over(Order By J.Pay Desc) As Rnk 
    From thePerson As P 
     Join hire As H 
      On H.PersonId = P.Person 
     Join theJobs As J 
      On J.JobId = H.JobId 
    ) 
Select ... 
From RankedPay 
Where Rnk = 1 
0
SELECT p.Person 
FROM person p JOIN hire h ON p.PersonID = h.PersonID 
    JOIN theJobs j ON h.JobID = j.JobID 
ORDER BY j.Pay DESC 
LIMIT 1; 

如果您使用的是不支持LIMIT子句的RDBMS,請嘗試使用TOP條款改爲:

SELECT TOP 1 p.Person 
FROM person p JOIN hire h ON p.PersonID = h.PersonID 
    JOIN theJobs j ON h.JobID = j.JobID 
ORDER BY j.Pay DESC