带有子句的SQL的问题

时间:2013-09-25 14:28:22

标签: sql

当我尝试执行下面的sql时,我收到一条错误消息,指出无效的列名称距离。我没有在我的sql中发布那么多,所以我不确定这是什么。在此先感谢您的帮助!

SELECT ID, 
  3959 * ACOS(COS(RADIANS(34.743305)) 
     * COS(RADIANS(Lattitude)) * COS(RADIANS(Longitude) - RADIANS(- 85.059586)) 
     + SIN(RADIANS(34.743305)) * SIN(RADIANS(Lattitude))) AS distance
FROM RetailerRegistration
HAVING (distance < 25)

3 个答案:

答案 0 :(得分:5)

问题是你试图引用你在SELECT列表中创建的别名,我建议使用子查询然后使用你的别名:

select ID, distance
from
(
  SELECT ID, 
    3959 * ACOS(COS(RADIANS(34.743305)) 
       * COS(RADIANS(Lattitude)) * COS(RADIANS(Longitude) - RADIANS(- 85.059586)) 
       + SIN(RADIANS(34.743305)) * SIN(RADIANS(Lattitude))) AS distance
  FROM RetailerRegistration
) d
where distance < 25;

处理查询的逻辑顺序是:

  1. FROM
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. 选择
  6. ORDER BY
  7. 因此,尚未为WHERE子句定义别名distance。解决这个问题的一种方法是使用子查询。

答案 1 :(得分:0)

havinggroup by一起使用。我认为你把它与where混淆了......另外,尝试将公式放入where子句而不是引用别名。

SELECT ID, 
  3959 * ACOS(COS(RADIANS(34.743305)) 
     * COS(RADIANS(Lattitude)) * COS(RADIANS(Longitude) - RADIANS(- 85.059586)) 
     + SIN(RADIANS(34.743305)) * SIN(RADIANS(Lattitude))) AS distance
FROM RetailerRegistration
WHERE
  3959 * ACOS(COS(RADIANS(34.743305)) 
     * COS(RADIANS(Lattitude)) * COS(RADIANS(Longitude) - RADIANS(- 85.059586)) 
     + SIN(RADIANS(34.743305)) * SIN(RADIANS(Lattitude))) < 25

答案 2 :(得分:-1)

你没有使用任何组织..像这样做:

SELECT ID, 3959 * ACOS(COS(RADIANS(34.743305)) * COS(RADIANS(Lattitude)) * COS(RADIANS(Longitude) - RADIANS(- 85.059586)) + SIN(RADIANS(34.743305)) * SIN(RADIANS(Lattitude))) AS distance FROM RetailerRegistration where (distance < 25)

Having子句用于对行组进行condidtion而不是单个行

希望这会有所帮助......