在sql查询中显示层次结构(自我关系表)

时间:2014-04-11 12:59:32

标签: sql sql-server-2012

我的数据库中有一个自我关系表。我试图创建一个显示我的行的查询:

Father 1
SonofFather1
Sonoffather1
Father 2
SonofFather2
Sonoffather2
SonofFather2
Sonoffather2
Father 3
.
.
.

我拥有的是:

WITH parents AS
    (SELECT parent.* FROM SubjectBase as parent WHERE parent.ParentSubject IS NULL

    UNION ALL

    SELECT son.* FROM SubjectBase as son WHERE son.ParentSubject IS NOT NULL)
    SELECT * from parents;

但它首先归还父母,然后是儿子。 我怎样才能显示父母跟随其儿子?

0 个答案:

没有答案