Gor*_*ley 5 mysql sql group-by
我有一个 MySQL 表,数据如下:-
country | city
---------------
italy | milan
italy | rome
italy | rome
ireland | cork
uk | london
ireland | cork
Run Code Online (Sandbox Code Playgroud)
我想查询这个并按国家和城市分组,并计算城市和国家的计数,如下所示:-
country | city | city_count | country_count
---------------------------------------------
ireland | cork | 2 | 2
italy | milan | 1 | 3
italy | rome | 2 | 3
uk | london | 1 | 1
Run Code Online (Sandbox Code Playgroud)
我可以:-
SELECT country, city, count(city) as city_count
FROM jobs
GROUP BY country, city
Run Code Online (Sandbox Code Playgroud)
这给了我:-
country | city | city_count
-----------------------------
ireland | cork | 2
italy | milan | 1
italy | rome | 2
uk | london | 1
Run Code Online (Sandbox Code Playgroud)
有没有获取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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12977 次 |
| 最近记录: |