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
2
  • can get the number of staff based on Children Count? like 0 children 50 people, 1 child 60 people, etc?
    – jaleel
    Commented Mar 15, 2017 at 10:48
  • @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. Commented Mar 15, 2017 at 11:11
1

Try this

select S.pID,
(select isnull(COUNT(*),0) from children C where C.pID=S.pID)
from Staff S
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.

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
  • 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.
    – jarlh
    Commented Mar 15, 2017 at 8:51
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.