0

I have a table as follows

 --------------------------------
 ChildId | ChildName | ParentId |
 --------------------------------
    1    |     A     |    0     |
 --------------------------------
    2    |     B     |    1     |
 --------------------------------
    3    |     C     |    1     |
 --------------------------------

I would like to select data as -

 ---------------------------------------
     Id   |    Name    |     Childs    |
 ---------------------------------------
     1    |      A     |       2       |
 ---------------------------------------
     2    |      B     |       0       |
 ---------------------------------------
     3    |      C     |       0       |
 ---------------------------------------

The pseudo SQL statement should be like this-

SELECT ChildId AS Id, ChildName as Name, (Count (ParentId) Where ParentId=ChildId)

Any Help?

1
  • What if B has a child? Commented Nov 15, 2015 at 10:35

3 Answers 3

2

This will do the trick:

select t1.childid, t1.childname, count(*) as childs
from table t1
join table t2 on t1.childid = t2.parentid
group by t1.childid, t1.childname
Sign up to request clarification or add additional context in comments.

Comments

0

Something like this?

SELECT ChildId AS Id, ChildName as Name, (SELECT COUNT(*)  FROM TestCountOver T WHERE T.ParentID = O.ChildID) FROM TestCountOver O

but that would give you all the nodes plus children who shouldn't be part of the hierarchy

If you want only nodes with children then use a cte

;WITH CTE AS (
SELECT ChildId AS Id, ChildName as Name, (SELECT COUNT(*) FROM TestCountOver T WHERE T.ParentID = O.ChildID) Cnt FROM TestCountOver O
)
SELECT *
FROM CTE
WHERE Cnt > 0

1 Comment

Takes me forever to write the answer :P Giorgi's answer is the better bet
0

If there is only one level you can use the approach in your pseudo code. It should look like this:

SELECT 
    ChildId AS Id, 
    ChildName as Name, 
    (select Count(ParentId) from t t_inner Where ParentId=t_outer.ChildId) children
from t t_outer
-- optionally where clause to limit result to parents that have children
where exists (select 1 from t where ParentId in (t_outer.ChildId))

but if there can be more than one level you can solve it using a recursive query if you want the total number of children for a parent (including grand-children etc).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.