2016-09-23 4 views
0

5つ以上の都市を持つ国を引き抜こうとしています。グループSQLステートメント - 都市が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); 

+1

この記事をお読みください。 http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins.aspx –

答えて

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

使用回数彼らがnullsを持っている場合のために)...私からしかし+1。 – scsimon

+0

ええ、OPはそれに特化していませんでした。二重引用符( – SlimsGhost

+0

真の点)がある場合のために 'count(distinct city) 'を使用しなければならないかもしれません...そして、それはおそらくそれらのためにおそらくもっと良いでしょう – scsimon

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 
+1

グループがありません.... – scsimon

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 
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); 
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; 
関連する問題