Display Parent-Child relationship when Parent and Child are stored in same table

前端 未结 7 2003
生来不讨喜
生来不讨喜 2020-12-09 19:03

I have SQL Server table structure like below:

ID    Name     ParentID
-----------------------
1     Root       NULL
2     Business   1
3     Finance    1
4           


        
7条回答
  •  余生分开走
    2020-12-09 19:53

    I think the following query would work. I've not tested it.

    SELECT
    ID
    , name
    , (CASE WHEN parent_name IS NULL THEN '-' ELSE parent_name END)
    FROM
    RELATIONS
    , (SELECT 
    parentID
    , name AS parent_name
    FROM
    RELATION) PARENT
    WHERE
    RELATIONS.parentId = PARENT.parentId
    

    Basically, what I'm doing is doing is choosing parent information, and relating it to each tuple.

提交回复
热议问题