SQL Server:WHERE子句中的ROW_NUMBER()返回“无效的列名”

时间:2018-07-28 10:10:17

标签: sql-server where-clause common-table-expression row-number

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

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

  1. 世界上所有country_code
  2. 世界上所有city_name拍摄一次
  3. 每个城市的Latitudelongitude
  4. 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 

enter image description here

当我取消评论where countdown_order < '100'时问题就到了 查询返回我

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

enter image description here

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

我不确定下一步该怎么做。

2 个答案:

答案 0 :(得分:2)

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

但是,您可以在更高级别上进行操作,例如派生表或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 

答案 1 :(得分:1)

您也可以使用公用表表达式(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