如何在sql中找到具有多个最大值的组的最大值?
Posted
技术标签:
【中文标题】如何在sql中找到具有多个最大值的组的最大值?【英文标题】:How to find the maximum of a group with multiple maximas in sql? 【发布时间】:2021-05-24 20:07:56 【问题描述】:表格必须按部门分组,并且必须返回部门的最大数量
表 A:
Id | Name | Department |
---|---|---|
1 | John Abraham | HR |
2 | Michael Clarke | HR |
3 | Roy Thomas | Manager |
4 | Tom Jose | HR |
4 | Jerry Pinto | Manager |
表 B:
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 |
【问题讨论】:
【参考方案1】:你可以试试这样的:
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 |
+------+----------------+------------+--------+
然后,我们确保根据部门和两个子查询中的金额连接两个子查询。
【讨论】:
以上是关于如何在sql中找到具有多个最大值的组的最大值?的主要内容,如果未能解决你的问题,请参考以下文章