简体   繁体   English

SQL SELECT ID FROM MAX VALUE

[英]SQL SELECT ID FROM MAX VALUE

i have 3 table, 我有3张桌子

- 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 我想显示在1月到4月之间数量最多的名字

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. 但是employeeid sql显示错误。 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. 更好的是,如果您的员工在firstname属性中仅具有一个名称,则可能会错误地对同一名称进行分组。 So, to identify better the employee, I would add the idemployee to the group by sentence. 因此,找出更好的员工,我会在加idemployeegroup by句子。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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