• 1731. 每位经理的下属员工数量


    SQL架构

    Table: Employees

    +-------------+----------+
    | Column Name | Type     |
    +-------------+----------+
    | employee_id | int      |
    | name        | varchar  |
    | reports_to  | int      |
    | age         | int      |
    +-------------+----------+
    employee_id 是这个表的主键.
    该表包含员工以及需要听取他们汇报的上级经理的ID的信息。 有些员工不需要向任何人汇报(reports_to 为空)。
    

    对于此问题,我们将至少有一个其他员工需要向他汇报的员工,视为一个经理。

    编写SQL查询需要听取汇报的所有经理的ID、名称、直接向该经理汇报的员工人数,以及这些员工的平均年龄,其中该平均年龄需要四舍五入到最接近的整数。

    返回的结果集需要按照 employee_id 进行排序。

    查询结果的格式如下:

    Employees table:
    +-------------+---------+------------+-----+
    | employee_id | name    | reports_to | age |
    +-------------+---------+------------+-----+
    | 9           | Hercy   | null       | 43  |
    | 6           | Alice   | 9          | 41  |
    | 4           | Bob     | 9          | 36  |
    | 2           | Winston | null       | 37  |
    +-------------+---------+------------+-----+
    
    Result table:
    +-------------+-------+---------------+-------------+
    | employee_id | name  | reports_count | average_age |
    +-------------+-------+---------------+-------------+
    | 9           | Hercy | 2             | 39          |
    +-------------+-------+---------------+-------------+
    Hercy 有两个需要向他汇报的员工, 他们是 Alice and Bob. 他们的平均年龄是 (41+36)/2 = 38.5, 四舍五入的结果是 39.
    1. select
    2. s1.reports_to employee_id,e.name,s1.reports_count,s1.average_age
    3. from
    4. (select
    5. reports_to,count(employee_id) reports_count,round(avg(age)) average_age #所有经理的ID、直接向该经理汇报的员工人数,以及这些员工的平均年龄,其中该平均年龄
    6. from
    7. Employees
    8. where reports_to is not null
    9. group by reports_to
    10. ) s1 left join Employees e on s1.reports_to = e.employee_id #得到经理的名字
    11. order by employee_id

  • 相关阅读:
    我的JQuery随笔
    CentOS命令大全
    嵌入式开发:为什么无触摸手势对嵌入式GUI开发团队至关重要
    在Web服务器(IIS)上安装SSL证书并绑定网站
    Pytorch手撸Attention
    第十七章 源代码文件 REST API 教程(二)
    重装系统后原git项目报错
    万字长文!对比分析了多款存储方案,KeeWiDB最终选择自己来
    Python学习笔记--字符、变量、数据类型与注释
    快速弄懂C++中的this指针
  • 原文地址:https://blog.csdn.net/m0_69157845/article/details/125565905