我想弄清楚如何选择一个表格,其值是付费最高的人的身份。
所以,如果我有
表= theJobs
JobID Pay
----------
12345 10
12346 12
12347 13
table = thePerson
Person JobID
--------------
Person1 1
Person2 2
Person3 3
table = hire(FKs)
JobID PersonID
----------------
12345 2
12347 1
12346 3
我希望它显示最高付费人员,以便显示
Person1
我试图使用Max函数的位置,但似乎失败了。我对这些小组的功能非常苛刻。我想我更多地问如何使用组函数作为约束而不是任何东西。因为我之前有类似的问题。
答案 0 :(得分: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;
如果您使用的RDBMS不支持LIMIT
子句,请尝试使用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
答案 1 :(得分: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