在嵌套子查询中分组

时间:2014-11-02 11:30:57

标签: sql

我有两张桌子:

Researcher (ResId, Fname, Gname)
Book (bookID, ResID*, Descr)

我需要使用IN(我的任务条件之一)声明来显示超过5本书的研究人员名单。

我得到了以下似乎是逻辑的SQL查询,但它给出了错误。子查询本身就可以正常工作:

select  ResId, Fname
from Researcher
where ResId in
   (select Book.ResId, count(*)
   from Book
   group by Book.ResId
   having count(*) > 5
   )

3 个答案:

答案 0 :(得分:1)

这是否按预期工作?

Select  ResId, Fname
From Researcher r
Inner Join Book b on b.ResId = r.ResId
Group By r.ResId, r.FName
Having count(b.*) > 5

答案 1 :(得分:1)

where ResId in
   (select Book.ResId, count(*)

使用IN (Select...时,您只能在子查询中选择一列 将上述内容更改为:

where ResId in
   (select Book.ResId

答案 2 :(得分:1)

只删除count(*),如下所示:

select  ResId, Fname
from Researcher
where ResId in
   (select Book.ResId 
   from Book
   group by Book.ResId
   having count(*) > 5
   )