【问题标题】:Compute number of direct report for each employee in the organization (aggregation)计算组织中每个员工的直接下属人数(聚合)
【发布时间】:2020-04-11 08:01:47
【问题描述】:

仅供参考,我使用 Redshift SQL。

我有一个大致如下所示的数据库(该数据库有多个列,为简单起见,我将对其进行抽象)。

此表表示我的组织内的层次结构树。

employee    manager
--------    -------
daniel      louis
matt        martha
martha      kim
laura       matt
michael     martha
...

如您所见,matt 出现在两个不同的记录中,一个是员工,另一个是 laura 的经理。 Martha 出现在三份记录中,一份是员工,另外两份是经理。

我想找到一种方法来计算每个员工的直接下属人数。条件计数,其中条件可能是employee = manager

我想我可以使用子查询找到这些信息,然后将其加入,但我想知道是否有一种更“优雅”的方式可以利用窗口函数来做到这一点。

上表的预期输出为:

employee    manager    direct_reports
--------    -------    --------------
daniel      louis      0
matt        martha     1
martha      kim        2
laura       matt       0
michael     martha     0
...

【问题讨论】:

    标签: sql group-by amazon-redshift aggregate-functions window-functions


    【解决方案1】:

    我会用一个相关的子查询来解决这个问题:

    select 
        t.employee,
        t.manager,
        (select count(*) from mytable t1 where t1.manager = t.employee) direct_reports
    from mytable t
    

    这应该是一种非常有效的方法,尤其是在(employee, manager) 上有索引时。

    【讨论】:

    • 干得好!性能方面,我不确定你的和 Gordon 的哪个更有效,但我更喜欢你的内联方法。您能否详细说明您对指数(员工、经理)的评论?看来戈登的速度要快一些。
    • @DanielSegura:这两种方法都很好(并且都将利用我提到的索引)。我想哪一个表现最好将取决于您的数据分布。您需要针对您的真实数据对这两种解决方案进行基准测试才能找出答案。
    【解决方案2】:

    使用left join 和聚合:

    select em.employee, em.manager, count(ew.employee)
    from employees em left join
         employees ew
         on ew.manager = em.employee
    group by em.employee, em.manager;
    

    【讨论】:

    • 效果很好,戈登。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2015-12-26
    • 2021-07-09
    • 2020-06-28
    • 2022-01-27
    相关资源
    最近更新 更多