我正在尝试为我的类分配编写查询,但我特别遇到一个查询问题。我遇到问题的查询统计每个国家/地区的所有城市,并将其显示在最大数量的城市和最小数量的城市中。我想写的查询的确切定义是......
从国家/地区开始按降序列出国家/地区 数据库中最多的城市,以及以 数据库中城市数量最少的国家/地区。城市 具有相同数量的城市应按字母顺序排序 从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 :(得分: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
答案 1 :(得分:0)
从国家/地区开始按降序列出国家/地区 数据库中最多的城市,以及以 数据库中城市数量最少的国家/地区。城市 具有相同数量的城市应按字母顺序排序 从A到Z。
country with largest number of cities
或smallest number of cities
,我们需要使用GROUP BY
和COUNT
按国家/地区进行分组和计算城市descending order
使用city_count DESC
使用same 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