Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Ordering items by hierarchy without RBAR Expand / Collapse
Author
Message
Posted Monday, March 24, 2014 1:40 PM
SSC Eights!

SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!

Group: General Forum Members
Last Login: Monday, July 21, 2014 7:44 PM
Points: 817, Visits: 1,646
Hey all,

I feel like I already know the answer to this question, but it is eluding me ...

Say I have a table with two columns - ID and ParentID. Say this table has the following values:

ID ParentID
10 50
20 30
30 10
50 NULL

Now, say I want the following output from my query:

ID ParentID Order
10 50 2
20 30 4
30 10 3
50 NULL 1

Is there any way to get this result in a single query, without needing potentially infinite recursion or using a row-by-row comparaison?
Post #1554206
Posted Monday, March 24, 2014 2:32 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Today @ 8:36 PM
Points: 36,793, Visits: 31,252
Sure... you could do a 4 way self join but that's hardcoding levels.

Recursion isn't so bad here. It will do things by level, not by row.


--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #1554216
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse