2015-10-15 42 views
0

我有以下查詢聚合不應出現在WHERE子句中,即使我沒有條件,同時使用SUM

SELECT A.*,SUM(ISNULL(B.DEPTRAN_DEPOSIT,0)-ISNULL(B.DEPTRAN_WITHDRAWAL,0)) as BALANCE 
FROM DEPOSITFDMASTER A 
INNER JOIN DEPOSITTRANSACTION B ON A.DEPSUBTYPE_ID=B.DEPSUBTYPE_ID AND A.FD_ID=B.DEPOSIT_DATAID WHERE SUM(ISNULL(B.DEPTRAN_DEPOSIT,0)-ISNULL(B.DEPTRAN_WITHDRAWAL,0))>10 

這個當我嘗試執行我會得到下面的錯誤。如果我刪除condtion,那麼查詢將正常工作。

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. 

P.S:DEPTRAN_DEPOSITDEPTRAN_WITHDRAWAL兩者都具有數據類型Decimal(18,2)

任何幫助表示讚賞。

+0

改爲使用'HAVING'。 –

+0

你不能在'WHERE'中使用SUM。你需要對A的所有列進行分組並且使用have,或者使用帶有'OVER'子句的'SUM'。 –

回答

1

我建議你使用GROUP BY和HAVING。像這樣的東西

SELECT 
    A.* 
    ,SUM(ISNULL(B.DEPTRAN_DEPOSIT,0)-ISNULL(B.DEPTRAN_WITHDRAWAL,0)) as BALANCE 
FROM DEPOSITFDMASTER A 
INNER JOIN DEPOSITTRANSACTION B 
ON 
A.DEPSUBTYPE_ID=B.DEPSUBTYPE_ID 
AND  
A.FD_ID=B.DEPOSIT_DATAID 
GROUP BY [All columns in A] --like that A.Column1,A.COlumn2,....,A.ColumnN 
HAVING SUM(ISNULL(B.DEPTRAN_DEPOSIT,0)-ISNULL(B.DEPTRAN_WITHDRAWAL,0))>10