Yesterday, I posted this issue regarding Parent/Child ordering that I thought had been resolved.
The resultant query that worked for a while was:
S
What you can do is use a Revursive CTE
to find the RootId
which you can then use in the ORDER BY
;WITH c AS
(
SELECT NoteId, NoteId ParentNoteId, NoteId AS RootId, t.NoteText
FROM tbl
WHERE ParentNoteId = 0
UNION ALL
SELECT t.NoteId, t.ParentNoteId, c.RootId, t.NoteText
FROM tbl AS t
INNER JOIN c ON t.ParentNoteId = c.NoteId
WHERE t.NoteId <> 0
)
SELECT
c.NoteId,
CASE WHEN c.ParentNoteId = c.NoteId THEN 0 ELSE c.ParentNoteId END AS ParentId,
c.NoteText
FROM c
ORDER BY RootId, ParentNoteId, NoteId
Which give a result like (text ommitted)
NoteId ParentId
--------------------
23471 0
23472 23471
23473 23471
23478 23471
23481 23471
23474 23472
23475 23474
23476 0
23477 23476
23482 23476
23484 23482
23485 23482
23486 23482
23487 23482
23480 0
demo