Microsoft
Software
Hardware
Network
Question : Find bottom level of an SQL Tree
I have an SQL table used to store a heirarchial tree - each record has an id (icostcentre_id) and a parent (icostcentre_parentid). The parent points to the immediate parent costcentre OR IS null if this is a top level cost centre. As such it is easy to find top level cost centres using a query of
SELECT icostcentre_id WHERE icostcentre_parentid IS NULL
and pretty easy to traverse the tree using a simple WHERE icostcentre_parentid = value statement.
My problem is that I want to identify those records which have no children - that is the cost centres at the bottom of the tree. I did try :-
SELECT icostcentre_id FROM icostcentre
WHERE icostcentre_id NOT IN (SELECT DISTINCT(icostcentre_paren
tid) FROM icostcentre)
thinking that this would return all records whose ID was not referenced by any children but this returned no records - I assume there is a problem because I am comparing icostcentre_id with icostcentre_parentid???
Please can you suggest a way of quickly identifying those records which have no children?
Answer : Find bottom level of an SQL Tree
SELECT i1.icostcentre_id
FROM icostcentre i1
left outer join icostcentre i2 on i1.icostcentre_id= i2.icostcentre_parentid
WHERE i2.icostcentre_parentid is null
Random Solutions
varchar sort
Nvidia Geforce 8400M GS in a Sony Vaio SZ650N/C WINDOWS 7 INCOMPATIBLE?
what is the difference between utf-8 or utf-7 both are unicode
WinMgmt errors in event log, started after applying latest updates
User is still recieving email for an email address that was removed from their account and applied to another
Access Web front-End
How do I convert double to string?
Append string from editbox to text file
EM_FORMATRANGE gives insufficient memory when printing with PCL 6
how to run a batch file from an asp.net 2.0 web page?