几天以来,我一直在使用this免费和开源数据库,该数据库列出了世界上的所有IP地址。
我的目标是创建一个可以列出的数据库:
country_code
city_name
拍摄一次Latitude
和longitude
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'
时问题就到了
查询返回我
Msg 207, Level 16, State 1, Line 8
Invalid column name 'countdown_order'.
是的,我尝试使用CTE
,但是由于ORDER BY
,它返回了更多错误。
我不确定下一步该怎么做。
答案 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