在 MySQL 中,可以使用 GROUP BY 语句结合聚合函数和子查询来获取每个组中的最大和最小值对应的记录
假设有一个名为 your_table 的表,其中包含两列:group_column 和 value_column
要分别获取每个组中的最大和最小值对应的记录,可使用两条独立的 SQL 查询
获取最大值的记录:
SELECT t1.*
FROM your_table t1
JOIN (
SELECT group_column, MAX(value_column) AS max_value
FROM your_table
GROUP BY group_column
) t2 ON t1.group_column = t2.group_column AND t1.value_column = t2.max_value;
获取最小值的记录:
SELECT t1.*
FROM your_table t1
JOIN (
SELECT group_column, MIN(value_column) AS min_value
FROM your_table
GROUP BY group_column
) t2 ON t1.group_column = t2.group_column AND t1.value_column = t2.min_value;
这两个查询分别使用了子查询来获取每个组的最大和最小值,然后通过连接操作获取相应的记录。可根据自己的实际需求和表结构调整表名和列名
假设有一个名为 employees 的表,记录了不同部门员工的信息,包括部门名 (department)、员工名 (employee_name) 和工资 (salary)。现在要分别获取每个部门中工资最高和最低的员工信息
employees 表格:
+----+------------+---------------+--------+
| id | department | employee_name | salary |
+----+------------+---------------+--------+
| 1 | HR | Alice | 50000 |
| 2 | HR | Bob | 55000 |
| 3 | IT | Charlie | 60000 |
| 4 | IT | David | 62000 |
| 5 | Sales | Emily | 70000 |
| 6 | Sales | Frank | 68000 |
+----+------------+---------------+--------+
获取每个部门中工资最高的员工:
SELECT e1.*
FROM employees e1
JOIN (
SELECT department, MAX(salary) AS max_salary
FROM employees
GROUP BY department
) e2 ON e1.department = e2.department AND e1.salary = e2.max_salary;
这将返回每个部门中工资最高的员工记录:
+----+------------+---------------+--------+
| id | department | employee_name | salary |
+----+------------+---------------+--------+
| 2 | HR | Bob | 55000 |
| 4 | IT | David | 62000 |
| 5 | Sales | Emily | 70000 |
+----+------------+---------------+--------+
获取每个部门中工资最低的员工:
SELECT e1.*
FROM employees e1
JOIN (
SELECT department, MIN(salary) AS min_salary
FROM employees
GROUP BY department
) e2 ON e1.department = e2.department AND e1.salary = e2.min_salary;
这将返回每个部门中工资最低的员工记录:
+----+------------+---------------+--------+
| id | department | employee_name | salary |
+----+------------+---------------+--------+
| 1 | HR | Alice | 50000 |
| 3 | IT | Charlie | 60000 |
| 6 | Sales | Frank | 68000 |
+----+------------+---------------+--------+