SQL Server Parent/Child CTE Ordering issue revisited

前端 未结 1 1056
忘了有多久
忘了有多久 2021-01-17 06:12

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         


        
相关标签:
1条回答
  • 2021-01-17 06:56

    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

    0 讨论(0)
提交回复
热议问题