gpt4 book ai didi

SQL QUERY 选择特定老板手下的员工

转载 作者:行者123 更新时间:2023-12-04 16:47:38 25 4
gpt4 key购买 nike

一个具有挑战性的问题,我有如下表格

员工ID 老板ID

pic http://img16.imageshack.us/img16/7659/20130430113245.jpg

创建查询的任何想法,以便当某个员工进入时,它将查询他下面的所有员工以及他的老板是谁

最佳答案

试试这个查询

你必须使用 Sohail 提到的 CTE。

WITH DirectReports (bossId, EmpID, Level)
AS
(
-- Anchor member definition
SELECT bossId, empId,
0 AS Level
FROM tbl
WHERE empId = 2
UNION ALL
-- Recursive member definition
SELECT e.bossId, e.empId,
Level + 1 AS Level
FROM tbl e
INNER JOIN DirectReports AS d
ON e.bossId = d.empId
)
-- Statement that executes the CTE
SELECT *
FROM DirectReports;

SQL FIDDLE

| BOSSID | EMPID | LEVEL |
--------------------------
| 1 | 2 | 0 |
| 2 | 4 | 1 |
| 4 | 5 | 2 |
| 4 | 6 | 2 |

关于SQL QUERY 选择特定老板手下的员工,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16291824/

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