我有两张桌子 - 一张用于工作人员,另一张用于子女。
如何根据儿童人数对人进行分组?
员工表
pID|name|family|ETC|
---- |-------- |-------|-------|
123 |abc|ddd | 134 | f |
124 |dfv |eee | 900 | d |
126 |rgt |wwww|750|m|
儿童表
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|
预期表格
pID|no|
----- |- |
123 |3|
124 |0|
126 |1|
答案 0 :(得分:2)
从staff
加入children
,按pID
分组将为您完成工作:
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
答案 1 :(得分:0)
试试这个
select S.pID,
(select isnull(COUNT(*),0) from children C where C.pID=S.pID)
from Staff S
答案 2 :(得分:0)
select s.pId
, (select count(*) from [children] c where c.pId = s.pId)
from [staff] s;
将[children]和[staff]替换为您的实际表名。
答案 3 :(得分:0)
SELECT staff.pid,count(*) FROM staff,children WHERE staff.pid=children.pid GROUP BY staff.pid;
此查询将为您提供结果输出。
答案 4 :(得分:0)
如果你想要所有PiD的结果(即使他们是0个孩子),那么使用:
select
staff.pID,count(children.name) as count
from staff
left outer join childern on childern.pID = staff.pID
group by S.pID
(Andy Korneyev的答案相同)
但是,如果您只想让孩子数(大于0),请使用:
select
staff.pID,count(children.name) as count
from staff
inner join childern on childern.pID = staff.pID
group by S.pID
希望这有帮助。