【问题标题】:How to find the maximum of a group with multiple maximas in sql?如何在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

【问题讨论】:

    标签: mysql sql database group-by max


    【解决方案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 |
    +------+----------------+------------+--------+
    

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

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多