[英]Sql get MAX for other value
I would like to figure out how to select a table where the value is the ID of the person with the highest pay. 我想弄清楚如何选择一个表,该表的值是薪水最高的人的ID。
So if I had 所以如果我有
Table=theJobs 表格=工作
JobID Pay
----------
12345 10
12346 12
12347 13
table=thePerson table = thePerson
Person JobID
--------------
Person1 1
Person2 2
Person3 3
table=hire(FKs) table =雇用(FKs)
JobID PersonID
----------------
12345 2
12347 1
12346 3
I'd like it to show the max payed person so it should show 我希望它显示最高工资的人,所以它应该显示
Person1
I tried to use where for the a Max function but it seems to fail. 我尝试对max函数使用where,但是它似乎失败了。 I'm pretty sucky at these group functions.
这些组函数让我感到很困惑。 I guess I'm more asking how to use a group function as a constraint than anything.
我想我问的更多的是如何使用组函数作为约束。 Since I had a similar issue a bit ago.
因为我之前有类似的问题。
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;
If you are using a RDBMS that does not support the LIMIT
clause, try using the TOP
clause instead: 如果使用的是不支持
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
This solution will work in pretty much any database system: 该解决方案几乎可以在任何数据库系统中工作:
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
)
If you are using a DBMS that supports ranking functions and common-table expressions such as SQL Server 2005 and later, then the problem is easier. 如果使用支持排名功能和公用表表达式(例如SQL Server 2005和更高版本)的DBMS,则此问题会更容易。 This solution will show only one name and ignore ties:
此解决方案将仅显示一个名称,并忽略联系:
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
This solution will show any that match the top pay and include ties: 此解决方案将显示所有与最高薪资相匹配并包含平局的人:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.