Reputation: 769
I am trying to order the results from SQL so that an indented BOM nests the values in the correct order. I got the "hard" recursive part done, but now getting the results to nest correctly is proving to be more problematic than I would have imagined. There do not seem to be any duplicates of this exact question in my rather extensive research thus far.
Here is my data:
+------+------------+-------+-----+-------+
| Root | Assemblys | Items | Qty | Depth |
+------+------------+-------+-----+-------+
| Root | Assembly | Item1 | 1 | 0 |
| Root | Item1 | Item2 | 3 | 1 |
| Root | Item1 | Item3 | 4.6 | 1 |
| Root | Item2 | Item4 | 1.5 | 2 |
| Root | Item2 | Item5 | 22 | 2 |
| Root | Item3 | Item6 | 6 | 2 |
+------+------------+-------+-----+-------+
What I'm looking to do is sort the columns so that one column follows the values from another column. Notice how Item1 has its assemblies moved to be right after it appears in the items row? I have tried to figure out how to use one column to sort another column, but so far no luck with anything I've tried.
+------+-----------+-------+-----+-------+
| Root | Assemblys | Items | Qty | Depth |
+------+-----------+-------+-----+-------+
| Root | Assembly | Item1 | 1 | 0 |
| Root | Item1 | Item2 | 3 | 1 |
| Root | Item2 | Item4 | 1.5 | 2 |
| Root | Item2 | Item5 | 22 | 2 |
| Root | Item1 | Item3 | 4.6 | 1 |
| Root | Item3 | Item6 | 6 | 2 |
+------+-----------+-------+-----+-------+
Upvotes: 1
Views: 916
Reputation: 117606
You can use recursive CTE, something like this:
;with cte as (
select *, cast([Item] as nvarchar(max)) as [path] from IndentedBOM where Depth = 0
union all
select i.*, c.[path] + '/' + i.[Item]
from cte as c
inner join IndentedBOM as i on i.[Assembly] = c.[Item]
)
select *
from cte
order by [path]
Upvotes: 2