一个具有挑战性的问题,我有如下表格
EmployeeID BossID
pic http://img16.imageshack.us/img16/7659/20130430113245.jpg
创建查询的任何想法,以便当某个员工进入时,它会查询他下面的所有员工以及谁是他的老板
答案 0 :(得分:5)
尝试此查询
你必须像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;
| BOSSID | EMPID | LEVEL |
--------------------------
| 1 | 2 | 0 |
| 2 | 4 | 1 |
| 4 | 5 | 2 |
| 4 | 6 | 2 |
答案 1 :(得分:3)
您应该使用CTE(公用表表达式)创建查询。如需帮助,请阅读Recursive Queries
以下是您可以根据需要修改的类似示例,但这会有所帮助。
这是一个表结构。
CREATE TABLE [dbo]。[分类]( [Id] [bigint] IDENTITY(1,1)NOT NULL, [CategoryName] varchar NULL, [ParentId] [bigint] NULL)
这是分层查询。我刚刚为它创建了一个视图,因为我需要在我的场景中更多地过滤它。
CREATE VIEW [dbo].[CategoriesWithNameHierarchy] AS WITH Categories_Tree AS
(SELECT c.id AS 'Id' ,
0 AS 'Level',
c.CategoryName AS 'CategoryName',
cast(c.CategoryName AS varchar(30)) AS 'CNameHierarchy'
FROM Categories c
WHERE ParentId IS NULL
UNION ALL SELECT ChildCategories.Id AS 'Id',
(1 + ct.[Level]) AS 'Level',
ChildCategories.CategoryName AS 'CategoryName',
cast(ct.CNameHierarchy + '>' + ChildCategories.CategoryName AS varchar(30)) AS 'CNameHierarchy'
FROM Categories ChildCategories,
Categories_Tree ct
WHERE ChildCategories.ParentId = ct.Id)
SELECT *
FROM Categories_Tree
希望这会有所帮助。