2015-10-06 97 views
0

以下查詢返回需要的內容,但我需要修改它,以便我可以從 只選擇DocID數大於3的文檔中的記錄以及where子句中的內容。如果試圖這樣做,我總是得到錯誤:select with multiple where和count

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

我將如何編寫查詢,以滿足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

添加您的表的模式,以便我們能夠理解其中的DocID從何而來。你還使用哪個rdbms?它是SQLServer嗎? –

+0

你可以用'COUNT'函數向我們顯示你的查詢嗎? – Marusyk

+0

你是什麼意思的架構?它是dbo,是自動增量整數。 – korrowan

回答

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