如何在 sql 中找到具有多个最大值的组的最大值?

How to find the maximum of a group with multiple maximas in sql?

table必须按部门分组,返回部门的最大金额

Table答:

Id Name Department
1 John Abraham HR
2 Michael Clarke HR
3 Roy Thomas Manager
4 Tom Jose HR
4 Jerry Pinto Manager

Table乙:

M_Id Amount
1 5000
2 5000
3 2500
4 1000
4 1500

预期答案

Id Name Department Amount
1 John Abraham HR 5000
2 Michael Clarke HR 5000
3 Roy Thomas Manager 2500

您可以尝试这样的操作:

select main.*

FROM

-- get all information from t1 and amount from t2
(
  select t1.*, t2.amount from t1 inner join t2 on t1.id = m_id
) main

INNER JOIN

-- get max amount by department
(
  select department, max(amount) max_amount from t1 inner join t2 on t1.id = m_id
  group by department
) summary

-- match with main by department and the max amount
on main.department = summary.department
and main.amount = summary.max_amount;

结果

+------+----------------+------------+--------+
| id   | name           | department | amount |
+------+----------------+------------+--------+
|    1 | John Abraham   | HR         |   5000 |
|    2 | Michael Clarke | HR         |   5000 |
|    3 | Roy Thomas     | Manager    |   2500 |
+------+----------------+------------+--------+

例子在这里:https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=a4cdd94b415df204b0fd967263ba9dc8

说明

由于您想按部门获取最大金额,我们为此创建了一个子查询。我们给它起了一个别名summary。这给了我们这个:

select department, max(amount)
from t1 inner join t2 on t1.id = m_id group by department;
+------------+-------------+
| department | max(amount) |
+------------+-------------+
| HR         |        5000 |
| Manager    |        2500 |
+------------+-------------+

我们通过组合 t1 和 t2 表组合了您想要报告的数据,并为其指定了别名 main。这给了我们这个:

select t1.*, t2.amount from t1 inner join t2 on t1.id = m_id;
+------+----------------+------------+--------+
| id   | name           | department | amount |
+------+----------------+------------+--------+
|    1 | John Abraham   | HR         |   5000 | <-- want this
|    2 | Michael Clarke | HR         |   5000 | <-- want this
|    3 | Roy Thomas     | Manager    |   2500 | <-- want this
|    4 | Jerry Pinto    | Manager    |   1000 |
|    4 | Tom Jose       | HR         |   1000 |
+------+----------------+------------+--------+

然后,我们确保根据部门和两个子查询中的金额连接两个子查询。