GROUP BY mySQL语句

时间:2018-10-13 15:51:11

标签: mysql group-by

使用我的SQL列表,为每个国家/地区指定城市数。 您是否认为此声明意味着要计算每个国家的城市数量?

+----+----------------+---------+---------------+------------+
| id | name           | country | original-name | population |
+----+----------------+---------+---------------+------------+
|  1 | Kabul          | AFG     | Kabol         | 1780000    |
|  2 | Qandahar       | AFG     | Qandahar      | 237500     |
|  3 | Herat          | AFG     | Herat         | 186800     |
|  4 | Mazar-e-Sharif | AFG     | Balkh         | 127800     |
|  5 | Amsterdam      | NLD     | Noord-Holland | 731200     |
|  6 | Rotterdam      | NLD     | Zuid-Holland  | 593321     |
|  7 | Haag           | NLD     | Zuid-Holland  | 440900     |
|  8 | Utrecht        | NLD     | Utrecht       | 234323     |
|  9 | Eindhoven      | NLD     | Noord-Brabant | 201843     |
| 10 | Tilburg        | NLD     | Noord-Brabant | 193238     |
+----+----------------+---------+---------------+------------+

我的代码有效,但超过4000行:

SELECT name, country 
FROM city 
GROUP BY name, country 
ORDER BY country ASC;

1 个答案:

答案 0 :(得分:2)

您只需要GROUP BY country

SELECT country, COUNT(*) as count_of_cities_per_country
FROM city 
GROUP BY country 
ORDER BY country ASC;