简体   繁体   中英

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.

So if I had

Table=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

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. 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:

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM