簡體   English   中英

計算SQL中不同多列的出現次數

[英]Counting occurrences of distinct multiple columns in 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的干預?

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

你需要的是一組:

Select city, country, count(*) as counter
from usertable
group by city, country
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;

如果不。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM