更新时间:2023-02-04 23:18:47
出现这种情况是因为查询处理顺序很自然,如下:
This happens because of natural query processing order, which is the following:
FROM
开启
外层
WHERE
GROUP BY
CUBE
|ROLLUP
拥有
SELECT
DISTINCT
ORDER BY
TOP
您正在 SELECT
语句中指定别名.正如你所看到的,WHERE
在 SELECT
之前被处理,而 ORDER BY
在它之后.这就是原因.现在有什么解决方法:
You're assigning your alias in SELECT
statement. As you can see WHERE
is processed before SELECT
and ORDER BY
comes after it. That's the reason. Now what are the workarounds:
交叉申请
.这应该美化您的代码,并且是推荐的方法.CROSS APPLY
. This should beautify your code a bit and is recommended method.CROSS APPLY
将在 WHERE
语句之前分配别名,使其在其中可用.
CROSS APPLY
will assign alias before WHERE
statement, making it usable in it.
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语句
If you want to find out more. Please read this question: What is the order of execution for this SQL statement