选择多个where和count

时间:2015-10-06 16:05:54

标签: sql sql-server

以下查询返回所需内容但我需要修改它以便我可以 仅从DocID的数量大于3的文档中选择记录以及where子句中的记录。尝试这样做时,我总是收到错误:

  

聚合可能不会出现在WHERE子句中,除非它在a中   包含在HAVING子句或选择列表中的子查询以及列   被聚合是一个外部参考。

如何编写查询以满足DocID大于3的计数? DocID是文档表的PK。

use newCityCollection
select a.CaseNumberKey, a.SearchUserID, c.DocType, c.RelatedDocID
from documents c
JOIN   newCityCollection.dbo.PropertyInformation a ON C.CaseNumberKey = A.CaseNumberKey
where  c.DocType = 'Assignment' and c.RelatedDocID is null and a.ClientKey = 3 and (count(c.docID) > 3) 

1 个答案:

答案 0 :(得分:1)

删除WHERE子句的最后一部分并添加having子句:

  USE newCityCollection
SELECT a.CaseNumberKey, a.SearchUserID, c.DocType, c.RelatedDocID
FROM documents c
JOIN   newCityCollection.dbo.PropertyInformation a ON C.CaseNumberKey = A.CaseNumberKey
WHERE c.DocType = 'Assignment' and c.RelatedDocID is null and a.ClientKey = 3
GROUP BY a.CaseNumberKey, a.SearchUserID, c.DocType, c.RelatedDocID
HAVING count(c.docID) > 3
相关问题