SQL Server嵌套报告结构/分层结构

时间:2012-04-18 10:58:02

标签: sql sql-server-2008

我有一张这样的表

Id       Name        ReportingId
==
1        Stala       Null
2        Coma        1
3        Rita        1
4        Rosy        2
5        sss         4

我想要一个递归查询来查找单列中的所有报告ID。

例如,对于id 5,输出应始终为null

4
2
1
null

2 个答案:

答案 0 :(得分:3)

以下是使用递归公用表表达式(CTE)的示例:

; with  cte as
        (
        select  ReportingID
        from    YourTable
        where   id = 5
        union all
        select  yt.ReportingID
        from    YourTable yt
        join    cte
        on      cte.ReportingID = yt.id
        )
select  *
from    cte

Example on SQL Fiddle.

答案 1 :(得分:2)

这样的事情:

测试数据

DECLARE @T TABLE(Id int,Name VARCHAR(5),ReportingId INT)

INSERT INTO @T
VALUES
    (1,'Stala',Null),
    (2,'Coma',1),
    (3,'Rita',1),
    (4,'Rosy',2),
    (5,'sss',4)

<强>查询

;WITH CTE
AS
(
    SELECT
        NULL AS Id,
        t.ReportingId
    FROM
        @T AS t
    WHERE
        t.Id=5
    UNION ALL
    SELECT
        t.Id,
        t.ReportingId
    FROM
        @T AS t
        JOIN CTE
            ON t.Id=CTE.ReportingId
)
SELECT
    CTE.Id
FROM
    CTE

<强>结果

NULL
4
2
1