Solved

derived query

Posted on 2007-04-09
5
254 Views
Last Modified: 2008-02-01
Hi,
I have a table CH in SQL Server 2005 with columns ParentID (PK) and childID. ChildID could be the ParentID of Another ChildID. I want all the ChildID that are also the ParentIDs.

I have tried this:
Select ParentID From  (Select ChildID from ch) ch
   
But it does not work.
0
Comment
Question by:SA4
5 Comments
 
LVL 9

Accepted Solution

by:
gpompe earned 250 total points
ID: 18878502
Try this
select a1.ChildID from Ch a1 join Ch a2 on a1.ChildId=a2.ParentID
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 18878510
please try this:

WITH R ( ParentID, ChildID, Level )
AS (
   SELECT ParentID, ChildID, 0
   FROM CH
   WHERE ParentID IS NULl
UNION ALL
   SELECT c.ParentID, c.ChildID, R.Level + 1
   FROM R
   JOIN CH
     ON R.ChildID = CH.ParentID
   )
SELECT *
FROM R

http://www.eggheadcafe.com/articles/sql_server_recursion_with_clause.asp
0
 

Author Comment

by:SA4
ID: 18878786
thanks for the reply, I tried this:
WITH R ( ParentID, ChildID, Level )
AS (
   SELECT ParentID, ChildID, 0
   FROM CH
   WHERE ParentID IS NULl
UNION ALL
   SELECT c.ParentID, c.ChildID, R.Level + 1
   FROM R
   JOIN CH
     ON R.ChildID = CH.ParentID
   )
SELECT *
FROM R

But It does not give any result And I know that there are a few that I should be getting.
 
0
 
LVL 25

Assisted Solution

by:jrb1
jrb1 earned 250 total points
ID: 18879366
select parentid from ch where parentid in (select cihldid from ch)
0
 

Author Comment

by:SA4
ID: 18883354
thanks for your help.
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains all about SQL Server Piecemeal Restore with examples in step by step manner.
Creating and Managing Databases with phpMyAdmin in cPanel.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

947 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now