为什么在尝试执行此SQL语句时出现不明确的列名CountryID错误消息:

时间:2014-04-17 15:51:59

标签: c# sql

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

1 个答案:

答案 0 :(得分:1)

因为您按CountryID分组了两个表:CountryDetail和您的子查询。将您的GROUP BY更改为GROUP BY CD.CountryID, GrossLimit, UnsecuredLimit

事实上,我认为最佳做法是更改所有列引用,以便他们使用适当的别名进行限定:

GROUP BY CD.CountryID, CD.GrossLimit, CD.UnsecuredLimit