当父项在同一个表中时,识别最低的子记录 - 叶节点?

时间:2014-12-21 08:23:37

标签: sql sql-server-2008 select

我有一个包含父记录和子记录的表。子女的代数可能会有所不同,但这可以通过[ElementLevelID]字段来确定。所有记录都有[ElementID]但子记录的[ParentElementID]。以下代码返回三代子代的所有值,但可能会更少:

SELECT     
    tbElement_2.ElementID AS E, 
    tbElement_2.ParentElementID AS PE, 
    tbElement_2.Description AS D, 
    tbElement_2.ElementPath AS P
FROM
    tbElement 
INNER JOIN
    tbElement AS tbElement_2 
INNER JOIN
    tbElement AS tbElement_1 ON tbElement_2.ParentElementID = tbElement_1.ElementID ON tbElement.ElementID = tbElement_1.ParentElementID
WHERE     
    (tbElement.Status = 0) 
    AND (tbElement_1.Status = 0) 
    AND (tbElement_2.Status = 0) 
    AND (tbElement_2.ElementLevelID = 3)

UNION ALL

SELECT     
    tbElement_1.ElementID AS E, 
    tbElement_1.ParentElementID AS PE, 
    tbElement_1.Description AS D, 
    tbElement_1.ElementPath AS P
FROM 
    tbElement 
INNER JOIN
    tbElement AS tbElement_1 ON tbElement.ElementID = tbElement_1.ParentElementID
WHERE     
    (tbElement.Status = 0) 
    AND (tbElement_1.Status = 0) 
    AND (tbElement_1.ElementLevelID = 2)

UNION ALL

SELECT     
    ElementID AS E, 
    tbElement.ParentElementID AS PE, 
    Description AS D, 
    ElementPath AS P
FROM         
    tbElement
WHERE
    (Status = 0) AND (ElementLevelID = 1)

ORDER BY P

返回值:

ElementID ParentELementID Desc               ElementLevelID CombinedDesc
    '37841' 'NULL'        'Ceilings'         '1' 'Ceilings'
    '37842' '37841'       'Concrete Soffit'  '2' 'Ceilings/Concrete Soffit'
    '37843' '37842'       'Plaster'          '3' 'Ceilings/Concrete Soffit/Plaster' 

我想将结果限制为没有子记录的记录,即上面的最后一条记录。我尝试添加像AND (tbElement_2.ElementID NOT IN (SELECT tbElement_1.ParentElementID FROM tbElement_1))这样的子查询,但无法使其工作。

1 个答案:

答案 0 :(得分:0)

  CREATE TABLE tbElement
(
    ElementID INT,
    ParentElementID INT,
    [Description] VARCHAR(100),
    ElementLevelID INT
)

INSERT INTO tbElement
SELECT '37841', NULL,        'Ceilings',         1 UNION ALL
SELECT '37842', '37841',       'Concrete Soffit',  2  UNION ALL
SELECT '37843', '37842',       'Plaster',         3 UNION ALL
SELECT '37844', NULL,        'Ceilings',         1 UNION ALL
SELECT '37845', 37844,        'Ceilings',         2 UNION ALL
SELECT '37846', NULL,        'Ceilings',         1 




SELECT tb1.*
FROM tbElement tb1
LEFT JOIN tbElement tb2
ON tb1.ElementID = tb2.ParentElementID
WHERE tb2.ParentElementID IS NULL