为什么此SQL不起作用?
这:
6371 * ACos( Cos(RADIANS(Latitude)) * Cos(RADIANS('50.017466977673905')) * Cos(RADIANS('24.69924272460935') - RADIANS(Longitude)) + Sin(RADIANS(Latitude)) * Sin(RADIANS('50.017466977673905')) )
子句只是从搜索点计算顺序。
我正在将其别名(因为它太长了)到“距离”。
SELECT [Hotel Id], latitude, longitude, establishmentname, 6371 * ACos( Cos(RADIANS(Latitude)) * Cos(RADIANS('50.017466977673905')) * Cos(RADIANS('24.69924272460935') - RADIANS(Longitude)) + Sin(RADIANS(Latitude)) * Sin(RADIANS('50.017466977673905')) ) AS Distance FROM [dbo].[RPT_hotels] WHERE distance < '30' ORDER BY Distance
在这里,我用冗长的短语替换了“ Distance <30”,它可以正常工作。
我什至可以对列别名进行ORDER BY,这行得通!!?
SELECT [Hotel Id], latitude, longitude, establishmentname, 6371 * ACos( Cos(RADIANS(Latitude)) * Cos(RADIANS('50.017466977673905')) * Cos(RADIANS('24.69924272460935') - RADIANS(Longitude)) + Sin(RADIANS(Latitude)) * Sin(RADIANS('50.017466977673905')) ) AS Distance FROM [dbo].[RPT_hotels] WHERE 6371 * ACos( Cos(RADIANS(Latitude)) * Cos(RADIANS('50.017466977673905')) * Cos(RADIANS('24.69924272460935') - RADIANS(Longitude)) + Sin(RADIANS(Latitude)) * Sin(RADIANS('50.017466977673905')) ) < '30' ORDER BY Distance
我究竟做错了什么?
发生这种情况是由于自然的查询处理顺序,如下所示:
FROM
ON
OUTER
WHERE
GROUP BY
CUBE
ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP
您要在SELECT语句中分配别名。如您所见,它WHERE是在处理之前SELECT和ORDER BY之后处理的。那就是原因。现在有什么解决方法:
CROSS APPLY
CROSS APPLY将在WHERE语句之前分配别名,使其在其中可用。
SELECT [Hotel Id] , latitude , longitude , establishmentname , Distance FROM [dbo].[RPT_hotels] CROSS APPLY ( SELECT 6371 * ACos(Cos(RADIANS(Latitude)) * Cos(RADIANS('50.017466977673905')) * Cos(RADIANS('24.69924272460935') - RADIANS(Longitude)) + Sin(RADIANS(Latitude)) * Sin(RADIANS('50.017466977673905'))) ) AS T(Distance) WHERE distance < 30 ORDER BY Distance;
如果您想了解更多。请阅读以下问题:此SQL语句的执行顺序是什么