SQL Count()子行基于Parent的值

时间:2013-10-31 18:18:14

标签: mysql sql db2

我有一个父表

EventKey   Event Name
1001       Event 1
1002       Event 2
1003       Event 3

这是我的孩子表

EventKey   EventAssignee
1001       Assignee 11
1001       Assignee 12
1002       Assignee 21
1002       Assignee 22

以下是我的SQL查询

select p.EventKey As Event_Key,
       p.Event_Name As EventName,
       (select count(*) 
        from Child c 
        where c.eventkey = p.eventkey) As Assignee_Count
from ParentTable p

这给了我一个SQL Error意外令牌Child。请告诉我哪里出错了

期待输出

Event_Key Event_Name Assignee_Count
1001      Event 1    2    
1002      Event 2    2
1003      Event 3    0

2 个答案:

答案 0 :(得分:5)

试试这个:

select p.EventKey As EventKey , p.EventName As EventName, count(c.assignee) As Assignee_Count
from Parent p left join child c on p.EventKey=c.EventKey 
group by p.EventKey,p.EventName 

答案 1 :(得分:0)

尝试按子查询中的Event_Key进行分组

select count(*) 
  from Child c 
  where c.eventkey = p.eventkey 
  group by p.eventkey