我一直遇到问题。我需要得到的是AVERAGE率最高的前3个国家。
SELECT TOP 3
Country, AVG(AverageRate) AS 'AverageRate'
FROM
dbo.CountryOrders
WHERE
OrderDate BETWEEN '2011-01-01' AND '2011-12-31'
GROUP BY
Country
ORDER BY
'AverageRate' DESC;
GO
答案 0 :(得分:1)
问题是单引号是AverageRate
。仅对字符串和日期常量使用单引号。你在这里不需要它们,所以只需删除它们:
SELECT TOP 3 Country, AVG(AverageRate) AS AverageRate
FROM dbo.CountryOrders
WHERE OrderDate BETWEEN '2011-01-01' AND '2011-12-31'
GROUP BY Country
ORDER BY AverageRate DESC;
您通过一个常量值(字符串'AverageRate')排序查询失败。如果需要转义标识符,请使用双引号或方括号(Sybase和SQL Server特定的)。
答案 1 :(得分:0)
这应该有效:
SELECT TOP 3 Country, AVG(AverageRate) AS 'AverageRate'
FROM dbo.CountryOrders
WHERE OrderDate BETWEEN '2011-01-01' AND '2011-12-31'
GROUP BY Country
ORDER BY AVG(AverageRate) DESC;
GO