"列名无效" SQL中的错误

时间:2016-04-23 09:17:00

标签: sql sql-server select group-by where

此代码有什么问题?

我收到此错误:

  

列名称无效'距离'

代码:

SELECT 
    Company.CompanyId as Id,
    ( 6371  * acos( cos( radians(47.8423155) ) * cos( radians( Company.Latitude  ) ) * cos( radians( Company.Longitude  ) - radians(35.232933) ) + sin( radians(47.8423155) ) * sin( radians( Company.Latitude ) ) ) ) AS Distance
FROM 
    Company 
INNER JOIN  
    Product ON Company.CompanyId = Product.CompanyId 
WHERE
    Distance< 5000   
ORDER BY
    Distance

2 个答案:

答案 0 :(得分:2)

根据您使用的,某些RDBMS不允许引用whereorder by列中的列别名。只需使用实际的列名:

SELECT      Company.CompanyId as Id,
            Company.VisitCount AS myVisitCount 
FROM        Company
INNER JOIN  Product ON  Company.CompanyId = Product.CompanyId 
WHERE       Company.VisitCount < 5000   
ORDER BY    Company.VisitCount

答案 1 :(得分:0)

将选择内部包裹在子选择

   select * from(SELECT 
    Company.CompanyId as Id,
    ( 6371  * acos( cos( radians(47.8423155) ) * cos( radians( Company.Latitude  ) ) * cos( radians( Company.Longitude  ) - radians(35.232933) ) + sin( radians(47.8423155) ) * sin( radians( Company.Latitude ) ) ) ) AS Distance
FROM 
    Company 
INNER JOIN  
    Product ON (Company.CompanyId = Product.CompanyId) 
) AS P
WHERE
    P.Distance< 5000   
ORDER BY
    P.Distance;

内部子查询返回您使用别名Distance过滤的函数。