SQL 服务器:WHERE 子句中的 ROW_NUMBER() returns "Invalid column name"

SQL Server: ROW_NUMBER() in WHERE clause returns "Invalid column name"

几天以来,我一直在使用 this 免费开源数据库,该数据库列出了世界上所有的 IP 地址。

我的目标是创建一个可以列出的数据库:

  1. 世界上所有 country_code
  2. 世界上所有 city_name 拍摄一次
  3. 每个城市的
  4. Latitudelongitude
  5. 倒数订单 desc country_code

我做到了:

SELECT 
ROW_NUMBER() OVER (ORDER BY country_code desc,city_name desc) as countdown_order,
AVG(latitude) AS latitude, 
AVG(longitude) AS longitude, 
city_name, 
country_code
FROM ip2location_db11 
--where countdown_order < '100'
GROUP BY country_code, city_name
ORDER BY country_code, city_name 

当我取消注释 where countdown_order < '100' 时出现问题 查询returns我

Msg 207, Level 16, State 1, Line 8 
Invalid column name 'countdown_order'.

是的,我尝试使用 CTE,但由于 ORDER BY,它 returns 我出现了更多错误。

我不确定接下来要尝试什么。

countdown_order 是列别名。您不能在同一级别引用列别名。

但是,您可以在更高级别上执行此操作,例如派生 table 或 cte

SELECT *
FROM
(
    SELECT 
          ROW_NUMBER() OVER (ORDER BY country_code desc, 
                                      city_name desc) as countdown_order,
          AVG(latitude) AS latitude, 
          AVG(longitude) AS longitude, 
          city_name, 
          country_code   
    FROM  ip2location_db11 
    GROUP BY country_code, city_name
) as D
where countdown_order < 100   -- countdown_order is an integer, remove the single quote
ORDER BY country_code, city_name 

您也可以使用通用 Table 表达式 (CTE) 来实现。它看起来像这样:

;WITH MAIN_CTE AS (
SELECT 
          ROW_NUMBER() OVER (ORDER BY country_code desc, 
                                      city_name desc) as countdown_order,
          AVG(latitude) AS latitude, 
          AVG(longitude) AS longitude, 
          city_name, 
          country_code   
    FROM  ip2location_db11 
    GROUP BY country_code, city_name
) 
SELECT * FROM MAIN_CTE 
WHERE countdown_order < 100
ORDER BY country_code, city_name