Sorting nested set by name while keep depth integrity

Posted by wb on Stack Overflow See other posts from Stack Overflow or by wb
Published on 2010-06-16T17:00:10Z Indexed on 2010/06/16 17:02 UTC
Read the original article Hit count: 172

Filed under:
|
|

I'm using the nested set model that'll later be used to build a sitemap for my web site. This is my table structure.

create table departments (
    id int identity(0, 1) primary key
    , lft int
    , rgt int
    , name nvarchar(60)
);

insert into departments (lft, rgt, name) values (1, 10, 'departments');
insert into departments (lft, rgt, name) values (2, 3, 'd');
insert into departments (lft, rgt, name) values (4, 9, 'a');
insert into departments (lft, rgt, name) values (5, 6, 'b');
insert into departments (lft, rgt, name) values (7, 8, 'c');

How can I sort by depth as well as name? I can do

select
    replicate('----', count(parent.name) - 1) + ' ' + node.name
    , count(parent.name) - 1 as depth
, node.lft
from
    departments node
    , departments parent
where
    node.lft between parent.lft and parent.rgt
group by
    node.name, node.lft
order by
    depth asc, node.name asc;

However, that does not match children with their parent for some reason.

department      lft     rgt
---------------------------
 departments    0       1
---- a         1           4
---- d         1           2
-------- b     2           5
-------- c     2           7

As you can see, department 'd' has department 'a's children!

Thank you.

© Stack Overflow or respective owner

Related posts about sql

Related posts about hierarchy