我有两个带有以下字段的表
emp_table: emp_id, emp_name salary_increase: emp_id, inc_date, inc_amount
我需要编写一个查询,其中提供了雇员的详细信息,雇员获得加薪的次数,最大加薪金额的值以及该加薪的日期。这是我到目前为止所拥有的:
SELECT e.*, count(i.inc_amount), max(i.inc_amount) FROM salary_increase AS i RIGHT JOIN emp_table AS e ON i.emp_id=e.emp_id GROUP BY e.emp_id;
除了授予最高增加额的日期外,这正确地给出了所有要求。我尝试了以下方法,但均未成功:
SELECT e.*, count(i.inc_amount), max(inc_amount), t.inc_date FROM salary_increase AS i RIGHT JOIN emp_table AS e ON i.emp_id=e.emp_id RIGHT JOIN ( SELECT emp_id, inc_date FROM salary_increase WHERE inc_amount=max(inc_amount) GROUP BY emp_id ) AS t ON e.emp_id=t.emp_id GROUP BY e.emp_id;
这给出了错误“组功能的无效使用”。有人知道我在做什么错吗?
您不能WHERE inc_amount=max(inc_amount)在where子句中执行此操作,无论是在联接HAVING条件下使用还是在联接条件下执行,请尝试以下操作:
WHERE inc_amount=max(inc_amount)
HAVING
SELECT e.emp_id, e.inc_date, t.TotalInc, t.MaxIncAmount FROM salary_increase AS i INNER JOIN emp_table AS e ON i.emp_id=e.emp_id INNER JOIN ( SELECT emp_id, MAX(inc_amount) AS MaxIncAmount, COUNT(i.inc_amount) AS TotalInc FROM salary_increase GROUP BY emp_id ) AS t ON e.emp_id = t.emp_id AND e.inc_amount = t.MaxIncAmount;