我正在尝试使用WITH
T-SQL 创建分层查询。我想做的是,例如,直接或间接地确定 John 是否是 Ryan 的老板?
我该如何为此编写查询?
我正在尝试使用WITH
T-SQL 创建分层查询。我想做的是,例如,直接或间接地确定 John 是否是 Ryan 的老板?
我该如何为此编写查询?
WITH BossOf AS(
SELECT bossId, Id From Employees
UNION ALL
SELECT b.bossId, e.Id
FROM Employees AS e
INNER JOIN BossOf b ON b.Id = e.bossId
)
SELECT * FROM BossOf
WHERE Id = 'Ryan'
就像你可以用 BossOf 做的一个例子......
WITH BossOf AS(
SELECT bossId, Id From Employees
UNION ALL
SELECT b.bossId, e.Id
FROM Employees AS e
INNER JOIN BossOf b ON b.Id = e.bossId
)
SELECT * FROM Employees
WHERE Id IN (SELECT BossId
FROM BossOf
Where Id = 'Ryan')
甚至
WITH BossOf AS(
SELECT bossId, Id From Employees
UNION ALL
SELECT b.bossId, e.Id
FROM Employees AS e
INNER JOIN BossOf b ON b.Id = e.bossId
)
SELECT COUNT(*) FROM BossOf
WHERE Id = 'Ryan'
AND BossId = 'John'