我正在尝试使用WITH
的T-SQL创建分层查询。我想做的是,例如,直接或间接地找出John是否是Ryan的老板?
如何为此编写查询?
答案 0 :(得分:2)
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'