select
SQRT(
POWER(cast(Program_Latitude as float) - cast('41.5126237' as float), 2) +
POWER(cast(Program_Longitude as float) - cast('-81.6516411' as float), 2)
) * 62.1371192 AS DistanceFromAddress
from tblProgram
having DistanceFromAddress < 2
可以工作(尽管我认为没有,也没有 group by 子句)。
问题是您只能在where
子句中选择的表范围内使用名称。Where
是一个预过滤器,它在选择行之前过滤掉行,因此字段定义中的此类表达式尚未执行,因此别名不可用。
该Having
子句在分组后用作后过滤器,并且可以使用查询中的别名,尽管恐怕您需要一个实际的group by
子句(不确定)。
另一种方法是有一个子选择(派生表或在选择中选择),您首先选择每行的距离,然后仅选择与这些结果相关的距离。这将起作用:
select d.DistanceFromAddress
from
(select
SQRT(
POWER(cast(Program_Latitude as float) - cast('41.5126237' as float), 2) +
POWER(cast(Program_Longitude as float) - cast('-81.6516411' as float), 2)
) * 62.1371192 AS DistanceFromAddress
from tblProgram) d
where d.DistanceFromAddress < 2
或者您可以重复该表达式。这会使您的查询更难维护,但在某些情况下,这可能对您有用。例如,如果您不想返回实际距离,而只想返回该距离处的兴趣点的名称。在这种情况下,您只需要在where
子句中使用表达式,在这种情况下,可维护性参数就消失了,这个解决方案是一个完美的选择。
select
tblProgram.POIname
/* Only if you need to return the actual value
, SQRT(
POWER(cast(Program_Latitude as float) - cast('41.5126237' as float), 2) +
POWER(cast(Program_Longitude as float) - cast('-81.6516411' as float), 2)
) * 62.1371192 AS DistanceFromAddress */
from tblProgram
where
-- Use this if you only want to filter by the value.
SQRT(
POWER(cast(Program_Latitude as float) - cast('41.5126237' as float), 2) +
POWER(cast(Program_Longitude as float) - cast('-81.6516411' as float), 2)
) * 62.1371192 < 2