SQL developers, I have a badly planned database as task to learn a lot about SQL Server 2012.
SO, there is the table Elem
:
+-----------+----
I dont think it can be done in one select in whole case ,so that you can select all parents,grandparents ,... . One way how to do it is to join elem table to herself ,and thet it depends on how many levels of join you do , that level of childs,grandchilds will you get.
The solution can be somethink like this(for the second case )
this will select you all parents,childs and grandchilds
Select
parent.key as parent_key,
child.key as child_key,
grandchild.key as grandchild_key
from elem parent
join elem child on (elem.key=child.parentkey)
join elem grandchild on (child.key=grandchild.parentkey)
where parent.parentkey is null; -- this make you sure that first level will be parents
solution for the first case is just that you will connect tables not in style of 'key=parentkey' but oposite 'parentkey=key'.