Reputation: 12207
Since a few days I'm working with this free and open source database that lists all IP addresses in the World.
My goal is to create a database that could list:
country_code
in the worldcity_name
in the world taken onceLatitude
and longitude
of each citydesc
on the country_code
and I did it:
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
Problems arrives when I uncomment that where countdown_order < '100'
The query returns me
Msg 207, Level 16, State 1, Line 8
Invalid column name 'countdown_order'.
Yes, I tried using CTE
but it returns me more errors because of the ORDER BY
.
I'm not sure what to try next.
Upvotes: 0
Views: 1424
Reputation: 603
You could also do it using Common Table Expressions (CTEs). It looks something like this:
;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
Upvotes: 1
Reputation: 24763
countdown_order
is a column alias. You can't reference to the column alias at the same level.
However, you can do it at a higher level like a derived table or 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
Upvotes: 3