|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
How to implement this kind of sorting?
Here's a basic overview of my Table
ID identity int ParentID int Name varchar Now, the root level items will have a ParentID of NULL, and the child nodes will have it's parent's ID in it's ParentID column (a simple self-referencing relationship). However, when I select it, I would like to Order by ID, but then have all it's children right after it. For example, if this is the unsorted view: Code:
ID ParentID Name ---------------------- 1 <NULL> Test 2 1 Test Child 1 3 <NULL> Test 2 4 1 Test Child 2 5 3 Test 2 Child 1 I would like the sorted to look like: Code:
ID ParentID Name ---------------------- 1 <NULL> Test 2 1 Test Child 1 4 1 Test Child 2 3 <NULL> Test 2 5 3 Test 2 Child 1 Is this possible with my current structure? If not, how could I change it? |
|
#2
|
|||
|
|||
|
give this a shot...simple order by should take care of this.
Code:
select * from myTable where ParentID is not null order by ParentID, name ...note, the where clause is included so that you don't get all the parent records back, just take it out if you wanna see 'em. |
|
#3
|
|||
|
|||
|
Oh wait...you do want the NULL parentID's...sorry, my solution won't give you what you want...
|
|
#4
|
|||
|
|||
|
Figured it out:
Code:
SELECT ... FROM ... WHERE ... ORDER BY COALESCE (ParentID, ID), ID Easy when you use math ![]() |
|
#5
|
|||
|
|||
|
Except if I wanted this to go down more than one level... still working on that
![]() |
![]() |
| Viewing: Dev Shed Forums > Databases > MS SQL Development > How to implement this kind of sorting? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|