我的任务是选择表格中城市数量大于以加拿大为国家的城市数量的国家。我正在使用 sakila数据库中的城市和国家/地区表。现在,我有这样的东西:
SELECT country, COUNT(country) FROM ( city
INNER JOIN country ON country.country_id = city.country_id)
GROUP BY country
HAVING COUNT(country) >= 7 -- should be COUNT(country='Canada') or something like that
ORDER BY COUNT(country) DESC;
第四行的数字7是城市数量,其中“国家/地区”列等于“加拿大”,但我不知道如何使用SQL进行计数,也无法使用Google找到正确的方法。有什么建议吗?
答案 0 :(得分:1)
您需要在HAVING子句中添加一个子查询。
以下查询获取加拿大的城市数。
SELECT count(*)
FROM city
LEFT JOIN country ON city.country_id = country.country_id
WHERE country = 'Canada'
GROUP BY country
因此,您将其放入having子句中。
SELECT
country, COUNT(*)
FROM
city
INNER JOIN
country ON country.country_id = city.country_id
GROUP BY
country
HAVING
COUNT(country) >= (
SELECT count(*)
FROM city
LEFT JOIN country ON city.country_id = country.country_id
WHERE country = 'Canada'
GROUP BY country
)
ORDER BY
COUNT(country) DESC;