I have a Standard table, which sotres parent, child category relationship…like this.
id, parent, catName, sort
And I use the following query to create a recursive tree
;WITH cte AS (
SELECT 0 AS lvl, id, catName, parent,levels,sort,
CAST(id AS VARCHAR(128)) AS path
FROM CategoriesMap WHERE parent =0
UNION ALL
SELECT p.lvl + 1, c.id, c.catName, c.parent,c.levels,c.sort,
CAST(p.path + '_' + CAST(c.id AS VARCHAR) AS VARCHAR(128))
FROM CategoriesMap c
INNER JOIN cte p ON p.id = c.parent
)
SELECT
id,
catName AS catName,
lvl,
levels,
path,
parent,
sort
FROM cte
ORDER BY path
And the output is like this Image:

Look for the Row with value ASP.NET & CLASSIC ASP, these are the last leaf(children) for the technology > Software (parents), I want to sort the LAST CHILDREN of any given parent (last parent). I can have multiple parents for a given node (last child) & all I care about is sort the LAST Children (leaf) using the “Sort” column.
so basicly “Classic Asp” shoud be before “Asp.Net” (Last Column is SORT column in my image).
My query is fine, it returns the results as expected…only challenege is i want to SORT the last NODE using the SORT column in table, last node can have 3 or 4 children which I want to sort, all nodes above the last node are its parents (which are in correct order already).
I want output like this…. Internet > ISP’s > CableVision (1) :
Verizon (2) as you can see CableVision & Verizon have Sort Value of 1
& then 2, Now lets say we have Shopping > Coupons > Macys(0) : Sears
(2), same thing….I want Macys & Sears to be sorted…and its pretty
obvious their parents are Shopping > Coupons.
@Richard aka cyberkiwi, after applying your code, my sorting for Categories table is very random. output is below

Delaying the calculation of the
pathfor one level, so the final result set has the parent path (ppath) available:Not really sure why the above gives error. This will not: