mysql - 使用连接、分组依据和聚合函数的 SQL 选择查询

标签 mysql sql join group-by aggregate-functions

我有两个包含以下字段的表

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 子句中执行 WHERE inc_amount=max(inc_amount) ,要么使用 HAVING 要么在 join 的条件下执行,试试这个:

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;

关于mysql - 使用连接、分组依据和聚合函数的 SQL 选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20594953/

相关文章:

mysql - 蛋糕PHP : populating 2 fields with the same foreign key and write to database

java - 使用准备好的语句将字段更新到 php 数据库

SQL 查询 where 子句

MySQL 查询两表连接

c# - mysql查询从具有公共(public)字段的两个表中检索数据

sql - 计算客户之间共享了多少订单

MySQL数据删除无删除级联

objective-c - 如何加入 [Number numberWithChar : c]'s into an NSString?] 的 NSArray

c# - 将数组转换为简单字符串的 C# 方法/语法是什么?

mysql - 如何将返回的总和修剪到我想要的精度?