计算SQL中不同多列的出现次数

时间:2012-01-20 10:58:51

标签: sql

我正在尝试计算用户表中一组不同城市和国家/地区的出现次数。

该表格类似于:

userid  city       country
------  ---------  --------------
1       Cambridge  United Kingdom
2       London     United Kingdom
3       Cambridge  United Kingdom
4       New York   United States

我需要的是每个城市和国家/地区的列表,其中包含出现次数:

Cambridge, United Kingdom, 2
London, United Kingdom, 1
New York, United States, 1

目前我运行SQL查询来获取不同的对:

$array = SELECT DISTINCT city, country FROM usertable

然后将其读入PHP中的数组,并循环遍历数组,运行查询以计算数组中每行的每次出现次数:

SELECT count(*) FROM usertable
WHERE city = $array['city']
AND   country = $array['country']

我假设我对SQL缺乏掌握的东西 - 这样做的正确方法是什么,最好没有PHP的干预?

3 个答案:

答案 0 :(得分:16)

select city, country, count(*)
from usertable
group by city, country

答案 1 :(得分:5)

您需要的是一个小组:

Select city, country, count(*) as counter
from usertable
group by city, country

答案 2 :(得分:1)

SELECT cityandcountry, count(*) as occurrences FROM (
  SELECT DISTINCT concat(city, country) FROM tablename
) as baseview;

如果您想要预先格式化城市和国家/或

SELECT cityandcountry, count(*) as occurrences FROM (
  SELECT DISTINCT city, country FROM tablename
) as baseview;

如果没有。