Sql Server 2005查询问题

时间:2010-10-22 04:39:03

标签: sql sql-server-2005

我有一个包含以下字段的表

  • Supervisorid
  • EMPID

这就像推荐计划一样。一个人可以推荐他下面的3个人,即 3是指三个人即4 5 8同样4指的是9 10和11同样8指的是12,13它是这样的..

我想要一个查询来获得一个人说3下的总行数。

1 个答案:

答案 0 :(得分:3)

您可以使用递归CTE

像这样的东西

DECLARE @Table TABLE(
        Supervisorid INT,
        Empid INT
)

INSERT INTO @Table SELECT 3, 4
INSERT INTO @Table SELECT 3, 5
INSERT INTO @Table SELECT 3, 8

INSERT INTO @Table SELECT 4, 9
INSERT INTO @Table SELECT 4, 10
INSERT INTO @Table SELECT 4, 11

INSERT INTO @Table SELECT 8, 12
INSERT INTO @Table SELECT 8, 13

DECLARE @ID INT
SELECT  @ID = 3

;WITH Vals AS (
        SELECT  *
        FROM    @Table
        WHERE   SuperVisorID = @ID
        UNION ALL
        SELECT  v.SuperVisorID,
                t.Empid
        FROM    Vals v INNER JOIN
                @Table t    ON  v.Empid = t.Supervisorid
)
SELECT  SuperVisorID,
        COUNT(Empid) Total
FROM    Vals
GROUP BY    SuperVisorID