gpt4 book ai didi

sql - 我想在 SQL 中使用 Recursive 返回新列?

转载 作者:行者123 更新时间:2023-12-02 04:20:29 27 4
gpt4 key购买 nike

我有下面显示的列的表格

| Employee ID | Manager ID |
|:-----------:|:----------:|
| E068 | E067 |
| E071 | E067 |
| E229 | E069 |
| E248 | E144 |
| E226 | E223 |
| E236 | E241 |
| E066 | E001 |
| E067 | E001 |
| E144 | E001 |
| E223 | E001 |
| E001 | Null |
| E241 | Null |

我们确实有包含“Leader ID”的表

| Leader ID |
|-----------|
| E001 |
| E241 |

问题陈述:

这个问题是通过使用员工和他们的经理数据来识别经理的负责人。

关于:我们有一个员工 ID 和他们的经理 ID。请注意,经理 ID 来自员工 ID。因为每个经理都有一个比他们级别高的经理。

首先,我们将获取 Manager ID 列中的所有 UNIQUE ID。然后对于 Manager ID 列中的每个 ID,我们将查找它们各自的 Manager ID(Manager)然后我们将创建一个新的列名称 Leader,它将包含 Manager 的所有层次结构。

要求的输出:

| Employee ID | Manager ID  | Leader ID |
|-------------|-------------|-----------|
| E068 | E067 | E001 |
| E071 | E067 | E001 |
| E229 | E069 | E001 |
| E248 | E144 | E001 |
| E226 | E223 | E001 |
| E236 | E241 | E241 |
| E066 | E001 | E001 |
| E067 | E001 | E001 |
| E144 | E001 | E001 |
| E223 | E001 | E001 |

员工 ID 列包含唯一 ID,而经理 ID 包含重复 ID。

最佳答案

这是 WITH RECURSIVE 的典型示例

Using RECURSIVE, a WITH query can refer to its own output.

试试这个:

with recursive subordinates as
(select
employeid,
e.managerid,
e.managerid as leader
from employes e
where e.managerid in(select * from leaders) -- non recursive term
union
select
e.employeid,
e.managerid,
a.managerid as leader
from employes e
join subordinates a on a.employeid = e.managerid -- recursive term
) select * from subordinates

如文档中所述:

一个 WITH RECURSCIVE 总是由

组成
  1. 非递归术语
  2. UNIONUNION ALL
  3. 一个递归术语,唯一可以引用查询输出的术语

当前一次迭代没有输出时,recusion 终止。

关于sql - 我想在 SQL 中使用 Recursive 返回新列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60275261/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com