SQL select query using joins, group by and aggregate functions

﹥>﹥吖頭↗ 提交于 2019-12-21 05:21:33

问题


I have two tables with the following fields

emp_table: emp_id, emp_name
salary_increase: emp_id, inc_date, inc_amount

I am required to write a query which gives the employee details, the number of times an employee has received a salary increase, the value of the maximum increase amount and the date of that increase. Here is what i have so far:

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;

this correctly gives all the requirements apart from the date on which the maximum increase was awarded. I have tried the following with no success:

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;

this gives an error 'Invalid use of group function'. Does anyone know what i'm doing wrong?


回答1:


You can't do this WHERE inc_amount=max(inc_amount) in the where clause, either use HAVING or do it in the condition of join, try this instead:

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;


来源:https://stackoverflow.com/questions/20594953/sql-select-query-using-joins-group-by-and-aggregate-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!