SQL select查询使用连接,分组和聚合函数

Sti*_*ube 5 mysql sql join group-by aggregate-functions

我有两个表格,包括以下字段

emp_table: emp_id, emp_name
salary_increase: emp_id, inc_date, inc_amount
Run Code Online (Sandbox Code Playgroud)

我需要写一个查询,该查询给出了员工的详细信息,员工获得加薪的次数,最大增加金额的值以及增加的日期.这是我到目前为止:

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;
Run Code Online (Sandbox Code Playgroud)

这正确地给出了除了授予最大增加的日期之外的所有要求.我试过以下但没有成功:

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;
Run Code Online (Sandbox Code Playgroud)

这会给出错误"组功能的无效使用".有谁知道我做错了什么?

Mah*_*mal 5

您不能WHERE inc_amount=max(inc_amount)在where子句中执行此操作,无论是使用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;
Run Code Online (Sandbox Code Playgroud)