2014-10-12 152 views
0

我正在嘗試爲我的類分配編寫查詢,但特別是我遇到了一個查詢的問題。我遇到的問題涉及到每個國家的所有城市,並將它們從最多的城市顯示到最少的城市。我想寫的是查詢的確切定義...創建一個從多個表中獲取數據的查詢

名單的國家按降序排列與該國開始與 在數據庫中的城市數量最多,並與 國結束數據庫中最少的城市數量。城市 具有相同數量的城市應按照字母順序排序從A 到Z

我要現在就張貼了我與我使用完成表一起嘗試此查詢的代碼它。

SELECT country.name 
FROM what.country as name 
INNER JOIN what.city as city ON name.country_code = city.country_code 
SORT BY name DESC 

下面是我使用的兩個表格。

   Table "what.country" 
    Column  |   Type   |    Modifiers    
-----------------+-----------------------+-------------------------------------- 
country_code | character(3)   | not null default ''::bpchar 
name   | character varying(52) | not null default ''::character varying 
continent  | continent    | not null 
region   | character varying(26) | not null default ''::character varying 
surface_area | real     | not null default 0::real 
indep_year  | smallint    | 
population  | integer    | not null default 0 
life_expectancy | real     | 
gnp    | real     | 

      Table "what.city" 
    Column |   Type   |      Modifiers     
--------------+-----------------------+----------------------------------------- 
id   | integer    | not null default nextval('city_id_seq'::regclass) 
name   | character varying(35) | not null default ''::character varying 
country_code | character(3)   | not null default ''::bpchar 
district  | character varying(20) | not null default ''::character varying 
population | integer    | not null default 0 

回答

0

名單的國家按降序排列與該國開始與 在數據庫中的城市數量最多,並與 結束數據庫中城市數量最少的國家。城市 具有相同數量的城市應按照字母順序排序從A 到Z

  • 爲了找到country with largest number of citiessmallest number of cities我們需要使用GROUP BYCOUNT其中按國家分組計數城市
  • 對於descending order使用city_count DESCsame number of cities should be sorted alphabetically使用country_name

代碼

SELECT country.name AS country_name, COUNT(city.id) AS city_count 
FROM what.country as name 
INNER JOIN what.city as city ON name.country_code = city.country_code 
GROUP BY country.name 
ORDER BY city_count DESC, country_name 
+0

我很欣賞這個解釋,它真的幫了我很多! – ryan 2014-10-12 04:56:38

+0

不客氣。樂意效勞。 – Ram 2014-10-12 04:59:53

+0

提供的查詢在PostgreSQL中不起作用,因爲沒有'SORT BY'子句。 – vyegorov 2014-10-12 09:52:25

1

你可以嘗試做一個查詢爲:

SELECT A.name AS name, IFNULL(B.cities, 0) AS cities 
FROM what.country AS A 
LEFT JOIN (SELECT country_code, count(id) AS cities FROM what.city GROUP BY country_code) AS B 
ON A.country_code = B.country_code 
ORDER BY cities DESC, name ASC 
+0

好的,我會試試看,謝謝 – ryan 2014-10-12 04:41:01

相關問題