Sql查询如何按城市获取用户数

时间:2013-06-05 23:09:58

标签: sql group-by

想象一下下表Users

Users
------------------------

CITY        USERNAME        TOPIC 
city1        george          topic1
city1        george          topic2
city1        george          topic3
city1        chris           topic1
city1        chris           topic2
city2        john            topic1
city3        jenny           topic1

我希望按城市提供以下结果组

city1 -> 2 users
city2 -> 1 user
city3 -> 1 user

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:3)

如果您想要每个城市的不同用户:

select city, count(distinct username) TotalUsers
from users
group by city;

SQL Fiddle with Demo。结果是:

|  CITY | TOTALUSERS |
----------------------
| city1 |          2 |
| city2 |          1 |
| city3 |          1 |