如果在使用计算的ORDER BY时指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中

时间:2015-06-05 10:09:30

标签: sql sql-server tsql

我已经看到了对这个常见错误的一些回复,但没有一个符合我的特定查询。

我收到'如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中'

以下是查询:

SELECT DISTINCT TOP 40 LocatorID, DisplayAddress 
FROM [UKStreetsAndPlaces].[dbo].[OS_Locator] 
WHERE (SearchAddress LIKE 'Bal%') 
ORDER BY (Longitude + 0.537143) * (Longitude + 0.537143) + (Latitude - 51.253741) * (Latitude - 51.253741) ASC

我已经尝试将纬度和经度字段添加到SELECT行中,我也尝试为这些字段添加GROUP BY,但是我得到了同样的错误。

2 个答案:

答案 0 :(得分:2)

而是使用group by和聚合函数。我认为这样做你想要的:

SELECT TOP 40 LocatorID, DisplayAddress 
FROM [UKStreetsAndPlaces].[dbo].[OS_Locator] 
WHERE (SearchAddress LIKE 'Bal%') 
GROUP BY LocatorID, DisplayAddress 
ORDER BY MIN((Longitude + 0.537143) * (Longitude + 0.537143) + (Latitude - 51.253741) * (Latitude - 51.253741)) ASC;

答案 1 :(得分:1)

您需要按项目将订单添加到select语句中。即。

SELECT DISTINCT TOP 40 LocatorID, DisplayAddress, 
(Longitude + 0.537143) * (Longitude + 0.537143) + (Latitude - 51.253741) * (Latitude - 51.253741) as MyPosition 
FROM [UKStreetsAndPlaces].[dbo].[OS_Locator] 
WHERE (SearchAddress LIKE 'Bal%') 
ORDER BY (Longitude + 0.537143) * (Longitude + 0.537143) + (Latitude - 51.253741) * (Latitude - 51.253741) ASC