• 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

  • 相关阅读:
    网络通信过程
    TCGA下载和表达矩阵整理:最适合初学者的教程
    1.3 字符编码
    前端的几种网络请求方式
    大厂招聘IO常问面试题
    【无标题】
    互联网摸鱼日报(2023-10-14)
    设计与人工智能的关系,人工智能和建筑设计
    PE格式:手写PE结构解析工具
    中国1km土壤特征数据集(2010年)
  • 原文地址:https://blog.csdn.net/m0_69157845/article/details/125565905