1

I have two tables - one for staff and another for their children.

How can I group people on number of children?

staff table

pID|name|family|ETC|  
---- |-------- |-------|-------|    
123 |abc|ddd   | 134 | f |   
124 |dfv |eee   | 900 | d |     
126 |rgt |wwww|750|m|    

children table

pID|name|family|ETC|        
---- |-------- |-------|-------|    
123 |mah|ddd |2005/06/09|son |    
123 |dar|ddd |2013/11/01|girl|    
123 |sia|ddd |2003/01/01|girl|    
126 |naz|wwww|2007/25/01|girl|     

Expected table

pID|no|        
----- |- |    
123 |3|    
124 |0|    
126 |1|
1
  • Have you tried something yet? Commented Mar 15, 2017 at 8:02

5 Answers 5

4

Join from staff to children and grouping by pID will do the job for you:

select
    S.pID,
    count(C.name) as no
from staff as S
    left outer join childern as C on C.pID = S.pID
group by S.pID
Sign up to request clarification or add additional context in comments.

2 Comments

can get the number of staff based on Children Count? like 0 children 50 people, 1 child 60 people, etc?
@jaleel Why not? Just wrap the query into one more select grouping by no and counting pID - and you'll get exactly what you want.
1

Try this

select S.pID,
(select isnull(COUNT(*),0) from children C where C.pID=S.pID)
from Staff S

Comments

0
select s.pId
     , (select count(*) from [children] c where c.pId = s.pId)
  from [staff] s;

Replace [children] and [staff] with your actual table names.

Comments

0
SELECT staff.pid,count(*) FROM staff,children WHERE staff.pid=children.pid GROUP BY staff.pid;

This query will give you the resultant output.

1 Comment

Tip of today: Switch to modern, explicit JOIN syntax! Easier to write (without errors), easier to read and maintain, and easier to convert to outer join if needed.
0

If you want the result of all PiDs (Even if they 0 children) then use:

select
  staff.pID,count(children.name) as count
from staff
  left outer join childern on childern.pID = staff.pID
group by S.pID

(Same Answer as Andy Korneyev)

However, if you just want the children count (who have greater than 0) then use:

select
  staff.pID,count(children.name) as count
from staff
  inner join childern on childern.pID = staff.pID
group by S.pID

Hope this helps.

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.