我有一个 MySQL 表,其中的数据为:-
country | city
---------------
italy | milan
italy | rome
italy | rome
ireland | cork
uk | london
ireland | cork
我想查询这个并按国家和城市分组,并且有城市和国家的计数,如下所示:-
country | city | city_count | country_count
---------------------------------------------
ireland | cork | 2 | 2
italy | milan | 1 | 3
italy | rome | 2 | 3
uk | london | 1 | 1
我能做到:-
SELECT country, city, count(city) as city_count
FROM jobs
GROUP BY country, city
这给了我:-
country | city | city_count
-----------------------------
ireland | cork | 2
italy | milan | 1
italy | rome | 2
uk | london | 1
还有关于获取 country_count 的指示吗?
最佳答案
您可以使用相关子查询:
SELECT country, city, count(city) as city_count,
(SELECT count(*)
FROM jobs AS j2
WHERE j1.country = j2.country) AS country_count
FROM jobs AS j1
GROUP BY country, city
关于mysql - SQL Group By 和两列计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32901031/