2017-05-03 104 views
0

我有我的代碼問題,它似乎沒有接受我的選擇查詢中的聚合函數。我試圖用我的DATEDIFF(MONTH,MIN(LoanDateStart),MAX(LoanPaymentDue))實現的是我想要獲得總月數,然後使用查詢餘下的月份來計算月數。如何在Select語句中使用Aggregate

我得到這個錯誤:

Msg 130, Level 15, State 1, Line 11 Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

反正是有,我可以圍繞實現其他的方式?

查詢

SELECT 
ISNULL(SUM((CAST(((((lt.InterestRate/100) * lc.LoanAmount) + 
lc.LoanAmount)/((dbo.fnNumberOfYears(CONVERT(VARCHAR(15), LoanDateStart, 
101), CONVERT(VARCHAR(15), LoanPaymentDue, 101)) * DATEDIFF(MONTH, 
MIN(LoanDateStart), MAX(LoanPaymentDue))) * 2)) AS DECIMAL(18,2)))),0) 
FROM LoanContract lc 
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID 
WHERE lc.LoanTypeID = 1 AND lc.EmployeeID = 5 

回答

0

請嘗試以下...

SELECT ISNULL(SUM((CAST(((((lt.InterestRate/100) * 
            LoanContract.LoanAmount) + 
           LoanContract.LoanAmount)/
           ((dbo.fnNumberOfYears(CONVERT(VARCHAR(15), 
                   LoanDateStart, 
                   101), 
                 CONVERT(VARCHAR(15), 
                   LoanPaymentDue, 
                   101)) * 
            monthsDifference) * 
           2)) AS DECIMAL(18, 
                2)))), 
       0) 
FROM (SELECT LoanContractID AS LoanContractID, 
       DATEDIFF(MONTH, 
         MIN(LoanDateStart), 
         MAX(LoanPaymentDue)) AS monthsDifference 
     FROM LoanContract 
     GROUP BY LoanContractID 
    ) AS monthsDifferenceFinder 
INNER JOIN LoanContract ON LoanContract.LoanContractID = monthsDifferenceFinder.LoanContractID 
INNER JOIN LoanType lt ON lt.LoanTypeID = LoanContract.LoanTypeID 
WHERE lc.LoanTypeID = 1 
    AND lc.EmployeeID = 5 

請注意,我在主鍵的地方使用LoanContractIDLoanContract你有沒有說明了這是什麼。

您的問題的原因是,SUM()(聚合函數)是對的MIN()MAX(),本身聚集函數的結果運行。這個混淆SQL-Server

我已經通過編寫一個子查詢來解決這個問題,該子查詢根據每個記錄的主關鍵字LoanContract的唯一標識符確定每個LoanContract的兩個值之間的差異。 (是在3NF(第三範式數據)?)然後

子查詢的結果連接到LoanContract基於LoanContractID,有效地追加各LoanContractmonthsDifference值每條記錄爲LoanContract

SUM()然後能夠處理檢索到的值,而不必嘗試正確地聚合聚合值。

如果您有任何問題或意見,請隨時發佈相應評論。

+2

說明已添加到答案中。 – toonice

+0

感謝這個偉大的解釋,我現在完全明白爲什麼。非常感謝你@toonice –

+0

不客氣。很高興有幫助。 – toonice

0

反正我現在固定的問題,我使用LEFT OUTER JOIN

這裏是我的代碼:

SELECT 
ISNULL(SUM((CAST(((((lt.InterestRate/100) * lc.LoanAmount) + lc.LoanAmount)/((dbo.fnNumberOfYears(CONVERT(VARCHAR(15), LoanDateStart, 101), CONVERT(VARCHAR(15), LoanPaymentDue, 101)) * x.NumberOfMonths) * 2)) AS DECIMAL(18,2)))),0) 
FROM LoanContract lc 
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID 
LEFT OUTER JOIN(SELECT 
lc.LoanTypeID AS 'LoanTypeID', 
lc.EmployeeID AS 'EmployeeID', 
(DATEDIFF(MONTH, MIN(LoanDateStart), MAX(LoanPaymentDue))) AS 'NumberOfMonths' 
FROM LoanContract lc 
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID 
GROUP BY lc.EmployeeID, lc.LoanTypeID) x ON x.EmployeeID = lc.EmployeeID AND x.LoanTypeID = lc.LoanTypeID 
WHERE lc.LoanTypeID = 1 AND lc.EmployeeID = 5