Select distinct values with count in PostgreSQL

匆匆过客 提交于 2020-08-26 19:54:54

问题


This is a heavily simplified version of an SQL problem I'm dealing with. Let's say I've got a table of all the cities in the world, like this:

country city
------------
Canada  Montreal
Cuba    Havanna
China   Beijing
Canada  Victoria
China   Macau

I want to count how many cities each country has, so that I would end up with a table as such:

country city_count
------------------
Canada  50
Cuba    10
China   200

I know that I can get the distinct country values with SELECT distinct country FROM T1 and I suspect I need to construct a subquery for the city_count column. But my non-SQL brain is just telling me I need to loop through the results...

Thanks!


回答1:


Assuming the only reason for a new row is a unique city

select country, count(country) AS City_Count
from table
group by country


来源:https://stackoverflow.com/questions/24017693/select-distinct-values-with-count-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!