2014-02-15 265 views
0

我不斷遇到問題。我需要得到的是前3個AVG率最高的國家。SQL幫助:查詢問題

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 
+2

有什麼問題? – Joe

+2

您的數據庫是否支持「TOP 3」? – qqilihq

+1

在sql server 2005/2008'ORDER BY'不能看到別名。 – Mihai

回答

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 
+0

謝謝。這工作完美! – user3313555

+0

我很高興它做到了。請接受它作爲答案。 –

+0

這回答了這個問題!感謝你和@Gordon – user3313555

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特定)。

+0

謝謝...感謝 – user3313555