Vodka
Vodka

Reputation: 63

SQL SELECT ID FROM MAX VALUE

i have 3 table,

- Employee (idemployee, iddivision, firstname, lastname)
- Salary (idsalary, idemployee, dateadded, amount)
- division (iddivision, divisionname)

i want to display the first name that have the highest amount between january and april

so far i tried

SELECT firstname, MAX(Total) FROM (
SELECT firstname,SUM(amount) AS Total
FROM salary
JOIN employee ON employee.idemployee=salary.idemployee
WHERE dateadded BETWEEN "2019-1-1" AND "2019-4-1"
GROUP BY employee.idemployee) as t

but the employeeid sql show is wrong. why?

Upvotes: 0

Views: 403

Answers (2)

James
James

Reputation: 3015

SELECT employee.firstname, SUM(salary.amount) AS Total
FROM salary
  JOIN employee 
    ON employee.idemployee=salary.idemployee
WHERE salary.dateadded BETWEEN "2019-01-01" AND "2019-04-01"
GROUP BY employee.firstname
ORDER BY 2 DESC
LIMIT 1

You are filtering by the range you want, then you sum the amounts in that range, grouping by the employee. If you order by that sum and get just the first row, it must he one what you are looking for.

Even better, if your employees just have a name in the firstname attribute, you have the risk to group by the same name wrongly. So, to identify better the employee, I would add the idemployee to the group by sentence. Like this:

SELECT employee.idemployee, employee.firstname, SUM(salary.amount) AS Total
FROM salary
  JOIN employee 
    ON employee.idemployee=salary.idemployee
WHERE salary.dateadded BETWEEN "2019-01-01" AND "2019-04-01"
GROUP BY employee.idemployee,employee.firstname
ORDER BY 3 DESC
LIMIT 1

Upvotes: 2

Cameron Cloyd
Cameron Cloyd

Reputation: 21

Do you mean you want it to be ordered from greatest to least?

SELECT firstname, Total FROM (
SELECT firstname,SUM(amount) AS Total
FROM salary
JOIN employee ON employee.idemployee=salary.idemployee
WHERE dateadded BETWEEN "2019-1-1" AND "2019-4-1"
GROUP BY employee.idemployee) as t
order by desc Total

Upvotes: 1

Related Questions