New to CTE's and subqueries in SQL.
I have 3 tables:
categories (category_code, category)
countries (country_code, country, continent)
businesses (business, year_founded, category_code, country_code)
Goal is to look at oldest businesses in the world. I used a CTE:
WITH bus_cat_cont AS (
SELECT business, year_founded, category, country,
continent
FROM businesses AS b
INNER JOIN categories AS c1
ON b.category_code = c1.category_code
INNER JOIN countries AS c2
ON b.country_code = c2.country_code
)
SELECT continent,
category,
COUNT(business) AS n
FROM bus_cat_cont
WHERE n > 5
GROUP BY continent, category
ORDER BY n DESC;
The code works without WHERE n > 5
. But after adding that, I get the error:
column "n" does not exist
I realized there is a much easier way to get the output I want without a CTE.
But I'm wondering: Why do I get this error?