3

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

员工ID 老板ID

图片 http://img16.imageshack.us/img16/7659/20130430113245.jpg

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

4

2 回答 2

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;

SQL 小提琴

| BOSSID | EMPID | LEVEL |
--------------------------
|      1 |     2 |     0 |
|      2 |     4 |     1 |
|      4 |     5 |     2 |
|      4 |     6 |     2 |
于 2013-04-30T04:39:51.520 回答
3

您应该使用 CTE(公用表表达式)创建查询。如需帮助,您可以阅读递归查询

以下只是类似的示例,您可以根据需要进行修改,但这会有所帮助。

这是一个表结构。

CREATE TABLE [dbo].[Categories]( [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

希望这会有所帮助。

于 2013-04-30T04:10:27.713 回答