按语句分组 - 获取超过5个城市的国家/地区

时间:2016-09-23 19:50:43

标签: sql sql-server

我正试图拉动拥有超过5个城市的国家。

表:

城市 city_id, city, country_id, last_update

国家/地区 country_id, country, last_update

我认为我非常接近这个想法,但我并不完全在那里。有什么指针吗?

SELECT DISTINCT country
FROM country C, city O
WHERE O.country_id = C.country_id AND O.country_id
 IN (SELECT country_id FROM city group by country_id having count(country_id) > 5);

5 个答案:

答案 0 :(得分:4)

select country
from country inner join city on city.country_id = country.country_id
group by country
having count(distinct city) > 5

答案 1 :(得分:2)

Use the below query..

   SELECT country
    FROM country C
     JOIN city O
    ON  O.country_id = C.country_id 
    GROUP BY country
    HAVING count(distinct O.city)>5

答案 2 :(得分:1)

你可以这样尝试

select countryid, count(distinct city_id) from country c join city ct c.country_id=ct.country_id
group by countryid 
having count(distinct city_id) > 5

答案 3 :(得分:1)

SELECT DISTINCT 
       country
FROM   country C
WHERE EXISTS (SELECT COUNT(DISTINCT city_id)
              FROM city CITY
              WHERE CITY.country_id = C.country_id
              GROUP BY CITY.country_id 
              HAVING COUNT(DISTINCT city_id) > 5);

答案 4 :(得分:1)

以下查询适用于您的要求。

   SELECT C.country
     FROM country C
    INNER JOIN
          city O
       ON  O.country_id = C.country_id 
   GROUP BY C.country
   HAVING count(distinct O.city)>5;