Is it possible to craft an ORDER BY clause to ensure the following criteria for two fields (both of type INT), called child and parent respectively for this example.
parentreferenceschild, but can be null.- A parent can have multiple children; a child only one parent.
- A child cannot be a parent of itself.
- There must exist at least one child without a parent.
- Each value of
childmust appear before it appears inparentin the ordered result set.
I'm having difficulty with point 5.
Sample unordered data:
child parent
------------
1 NULL
3 5
4 2
2 5
5 NULL
Obviously neither ORDER BY a, b or ORDER BY b, a work. In fact the more I think about it, I'm not sure it can even be done at all. Given the restrictions, obvious cases such as:
child parent
------------
1 2
2 1
aren't allowed because it violates rule 3 and 4 (and obviously 5).
So, is what I am trying to achieve possible, and if so how? Platform is SQL Server 2005.
Update: Desired sort order for the sample data:
child parent
------------
1 NULL
5 NULL
2 5
3 5
4 2
For each row that defines a non-null value in the parent column, the value has already been present int the child column.