【发布时间】: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