M
M
mletov2017-02-01 09:43:23
SQL
mletov, 2017-02-01 09:43:23

How to sort Cte within a branch?

Please, could you tell me
There is a table with a fairly typical common structure: id, parent, sort, name
Something like this
1|Category_1 | Sort index 1 | ParentID 0
2|----Category_1.1 | Sort index 1 | ParentId 1
3|----Category_1.2 | Sort index 2 | ParentId 1
4|----Category_1.3 | Sort index 3 | Parent ID 1
5|Category_2 | Sort index 2 | Parent 0
6|----Category_2.1 | Sort index 1 | ParentID 5
7|----Category_2.2 | Sort index 2 | ParentID 5
8|----Category_2.3 | Sort index 3 | ParentID 5
9|--------Category_2.3.1 | Sort index 1 | Parent ID 8
10|--------Category_2.3.2 | Sort index 2 | ParentID 8
11|----Category_2.4 | Sort index 4| ParentId 5 I draw
the entire tree with cte.
You need to sort the selection by the sort field within each branch.
What options were given by Google and Stack Overflow:
1) They propose to make the sorting weight not within the framework of the branch, but through, and then glue it into one line and sort by the resulting field. Not a very pretty solution.
2) Refuse cte and write a store to get one branch, feed an id to get descendants as input and call it recursively
3) Recursively glue the id and sort by the result of concatenation
4) Well, I also wrote a solution using CASE WHEN, but it is a crutch, because it limits the number of levels and descendants for each branch.
Does anyone know a beautiful sorting solution specifically for cte?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question