I have a table category
as below:
id title ParentID
1 C1 0
2 C2 0
3 C3 0
4 C4 2
5 C5 1
6 C6 3
7 C7 4
I want result as
id title ParentID Level
1 C1 0 0
5 C5 1 1
2 C2 0 0
4 C4 2 1
7 C7 4 2
3 C3 0 0
6 C6 3 1
How can I get this result?
Explanation of the order: I want result with items below their parent item.
This answer assumes that you are using SQL Server 2008 or later.
Use a recursive CTE and build a string of id's that you use in the order by as a hierarchy id.
SQL Fiddle
With a recursive CTE, which basically builds the materialized path from root items to items:
Test at SQL-Fiddle