2016-10-21 7 views
-1

国の名前と国がある地区の数を提供するクエリを作成しようとすると、 地区の数が最高から最低までの結果を注文します。問題は、具体的には各国の地区数を数え、1つの国の横にある地区の総数を求めます。SQLクエリー:各国の地区数?

2つのテーブルは、国名(名称、コード)と都市名前、郡、国コード)。

Country.CodeとCity.CountryCodeは同じで、2つのテーブルに共通しています。

大変助かりました!

+1

テーブルをジョインするには、 'GROUP BY'を実行し、' COUNT(*) 'を使用します。 – jarlh

答えて

0
SELECT Name, noofdistricts 
    FROM 
     ( SELECT c.Name,COUNT(ci.District) AS noofdistricts 
      FROM Country c 
      JOIN City ci 
      ON c.code = ci.countrycode 
      GROUP BY c.Name 
     ) Z 
ORDER BY Name,noofdistricts DESC 
; 
+0

私は声明でグループを逃していました。 noofdistrictsの降順でこれらの結果を注文するにはどうすればいいですか? by order by by – Shane

+0

私はorder by節を追加しました。 pls check now – Teja

+0

これは私が言葉を語ったものですが、まだソートされていません。 – Shane

0

はその後JOINは私が正しくあなたを理解していれば、あなたが情報に基づいて、国にありますどのように多くのユニークな地区、この(カウントのようなものを探しているGROUP BY

よう
select c.Name, 
count(cc.District) as total_district 
from country c join city cc on c.code = cc.CountryCode 
group by c.Name 
order by total_district desc; 
0

が続くん

select 
    districts.country_name as country_name, 
    count(districts.district) as district_count 
from (  
    select unique --we want to count how many unique districts are there in a given country 
    country.code as country_code, 
    country.name as country_name, 
    city.district as district --we want to get districts where cities are located 
    from 
    Country country, 
    City city 
    where city.CountryCode = country.Code --join cities to countries 
) districts 
group by districts.country_code 
order by district_count desc 
関連する問題