I am using a nested set model that will later be used to create a sitemap for my website. 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 by 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, for some reason this does not match children with parents.
department lft rgt
departments 0 1
As you can see, department 'd' has department 'children!
Thank.