简体   繁体   中英

Finding the highest paid employee (Salary + Comm) in each department (dID)

Below is my table and I am trying to write a MySQL query that selects the highest paid employee (Salary + Comm) in each department (dID)

EmployeeID  | Name       | mgr | Job         | Salary| Com | HireDate     | dID
1001 | Ron Smith   | 1005| Writer| 90000 | 20000| 20012-04-12| 1
1002 | Ricky Lake  | 1003| Writer| 55000 | 15000| 2013-01-18| 1

This is what I have so far

SELECT dID, MAX(coalesce(Salary+Comm, Salary, Comm)) AS 'TotalPaid'
FROM Employee 
Group By dID

How do I go about allowing for the other columns to be shown? Hope I have explained what I want adequately thanks.

Here's one way:

select e.* from 
Employee e inner join 
(SELECT dID, MAX(coalesce(Salary+Comm, Salary, Comm)) as max_salary  AS 'TotalPaid'
FROM Employee 
Group By dID) d
on d.dID = e .dID 
and coalesce(e.Salary+e.Comm, e.Salary, e.Comm)=d.max_salary
SELECT dID, MAX(Salary+Comm) AS 'TotalPaid'
FROM Employee 

This will do the Job

SELECT
    E2.*, E3.TotalPaid
FROM
    Employee E2
INNER JOIN
    (
    SELECT
        MAX(eID) AS eID,
        dID,
        MAX(
            (
            SELECT
                MAX(
                    COALESCE(Salary + Comm, Salary, Comm)
                )
            FROM
                Employee E1
            WHERE
                E.eiD = E1.eID
        )
        ) AS 'TotalPaid'
    FROM
        Employee E
    GROUP BY
        dID
) AS E3
ON
    E2.eID = E3.eID

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