2

我有一个父表

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 错误意外令牌子项。请让我知道哪里出错了

我期望输出是

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

2 回答 2

7

试试这样:

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 
于 2013-10-31T18:36:33.460 回答
0

尝试在子查询中按 Event_Key 分组

select count(*) 
  from Child c 
  where c.eventkey = p.eventkey 
  group by p.eventkey
于 2013-10-31T18:37:57.067 回答