简体   繁体   中英

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?

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

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

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