SQL - 列名无效

时间:2011-03-24 10:32:30

标签: sql sql-server

我有以下查询:

SELECT o.outcode AS lead_postcode, v.outcode AS venue_postcode, 6 * o.lat AS distance 
FROM venue_postcodes v, uk_postcodes o 
WHERE o.outcode = 'CF3' 
GROUP BY v.outcode 
HAVING SUM(distance)>100 
ORDER BY distance

当我添加部件GROUP BY v.outcode HAVING SUM(distance)>100

时,此操作停止了

它说服务器无法处理请求。 --->列名称“距离”无效

任何想法为什么?

4 个答案:

答案 0 :(得分:6)

distance是列别名,您无法引用HAVING子句中的列别名。但您可以在ORDER BY中使用别名。

尝试更改为:

HAVING SUM(6 * o.lat)>100 
ORDER BY distance

答案 1 :(得分:2)

仅在查询中定义为“6 * o.lat”的“别名”距离尚未在查询中使用,但仅在之后使用。

替代解决方案是

SELECT i.*
FROM (
  SELECT o.outcode AS lead_postcode, v.outcode AS venue_postcode, 6 * o.lat AS distance 
  FROM venue_postcodes v, uk_postcodes o 
  WHERE o.outcode = 'CF3' 
) i
GROUP BY i.outcode 
HAVING SUM(i.distance)>100 ORDER BY i.distance

答案 2 :(得分:0)

使用ORDER BY 6 * o.lat。您不能对ORDER BY

使用AS条款

答案 3 :(得分:0)

我相信你需要使用SUM(6 * o.lat),因为不是每个数据库服务器都可以在having子句中使用别名列(它与查询规划,解析等有关)。取决于你使用的数据库。