我有3张桌子
- Employee (idemployee, iddivision, firstname, lastname)
- Salary (idsalary, idemployee, dateadded, amount)
- division (iddivision, divisionname)
我要显示在1月到4月之间数量最多的名字
到目前为止,我已经尝试过
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
但是employeeid sql显示错误。为什么?
答案 0 :(得分:1)
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
您正在按所需范围进行过滤,然后将该范围内的金额求和,并按员工分组。如果您按该总和排序并仅获得第一行,则它必须是您要查找的内容。
更好的是,如果您的员工仅在firstname属性中具有名称,则可能会错误地按相同的名称分组。因此,为了更好地确定员工,我将在idemployee
句子中添加group by
。像这样:
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
答案 1 :(得分:0)
您是说要从最大到最小排序吗?
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