想要获得在高级医生下工作的所有初级医生的名单,反之亦然?

时间:2012-02-27 09:43:21

标签: sql-server sql-server-2008

这是我的表DoctorInfo

|doctorId | firstname | seniorDoctorId |
   34         ABC          0
   35         XYZ          34
   36         bsd          34
   37         dfdf         35
   38         dffdg        0

1.如果我将doctorId设为34,将seniorDoctorId设为0,那么我希望输出为

 |doctorId | firstname | seniorDoctorId |
   34         ABC           0
   35         XYZ          34
   36         bsd          34
   37         dfdf         35

2.如果我将doctorId设为35,将seniorDoctorId设为34,那么我希望输出为

|doctorId | firstname | seniorDoctorId |
    35         XYZ          34
    37         dfdf         35

这是我的疑问:

select 
   doctorId,
   firstname,   
   seniorDoctorId
from DoctorInfo as a
where a.doctorId in
         (
             select 
                b.seniorDoctorId 
             from 
                DoctorInfo b 
             where 
                b.seniorDoctorId=@doid
         ) 
 or a.seniorDoctorId in
         (
             select 
                c.doctorId 
             from 
                DoctorInfo c
         )

2 个答案:

答案 0 :(得分:2)

这样的事情可能有所帮助:

首先是一些测试数据:

DECLARE @DoctorInfo TABLE
                (
                    doctorId INT,
                    fistName VARCHAR(100),
                    seniorDoctorId INT
                )

INSERT INTO @DoctorInfo
VALUES
    (34,'ABC',0),
    (35,'XYZ',34),
    (36,'bsd',34),
    (37,'dfdf',35),
    (38,'dffdg',0)

这样的查询:

DECLARE @doctorId INT
SET @doctorId=35
;WITH CTE(doctorId,seniorDoctorId,fistName)
AS
(
    SELECT
        DoctorInfo.doctorId,
        DoctorInfo.seniorDoctorId,
        DoctorInfo.fistName
    FROM
        @DoctorInfo AS DoctorInfo
    WHERE
        DoctorInfo.doctorId=@doctorId
    UNION ALL
    SELECT
        DoctorInfo.doctorId,
        DoctorInfo.seniorDoctorId,
        DoctorInfo.fistName
    FROM
        @DoctorInfo AS DoctorInfo
        JOIN CTE
            ON DoctorInfo.seniorDoctorId=CTE.doctorId
)
SELECT
    *
FROM
    CTE

要获得desierd输出,您不必使用seniorDoctorId,因为它们已经有父子关系。

参见示例here

答案 1 :(得分:1)

导航层次结构的一种方法是使用递归CTE。例如,要查找所有排名第34的医生,请尝试:

; with  ServantList as
        (
        select  *
        from    @DoctorInfo
        where   doctorId = 34
        union all
        select  di.*
        from    ServantList sl
        join    @DoctorInfo di
        on      sl.doctorId = di.seniorDoctorId
        )
select  *
from    ServantList

Example at SE Data.