SELECT
CD.CountryID, CD.GrossLimit, CD.UnsecuredLimit,
SUM(LT1.Amount), SUM(LT1.Unsecured), (100*SUM(LT1.Unsecured) / CD.UnsecuredLimit) as PercOverCountryLimit
FROM CountryDetail CD
INNER JOIN
(
SELECT CompanyName AS Company, CollateralSName as Collateral, SUM(Amount) AS Amount,
SUM(Usecured) AS Unsecured, LT.Date as Date, Max(LT.CountryID) as CountryID
FROM Loanstotal LT
WHERE YearMonth = @YearMonth
GROUP BY CompanyName, CollateralSName, LT.Date
) LT1
ON CD.CountryID = LT1.CountryID
GROUP BY CountryID, GrossLimit, UnsecuredLimit
Because you're grouping by CountryID
which is being returned by both tables: CountryDetail
and your sub-query. Change your GROUP BY
to GROUP BY CD.CountryID, GrossLimit, UnsecuredLimit
.
In fact, I think as a best practice you should change all your column references so they're qualified with the proper aliases:
GROUP BY CD.CountryID, CD.GrossLimit, CD.UnsecuredLimit
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.