mysql - SQL Group By 和两列计数

标签 mysql sql group-by

我有一个 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

Demo here

关于mysql - SQL Group By 和两列计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32901031/

相关文章:

mysql - 如何选择不属于用户组的用户结果集

sql - 当匹配的行存在于另一个表中时更新行

Mysql窗口函数的解决方法

php - 写入 PDO DELETE 查询值

c# - 如何使用 max(id) 作为 sql ce 中的搜索条件?

mysql - MySql Inner Join 的问题 > 未包含在聚合函数或 GROUP BY 子句中

sql - 在 Excel 中编辑 doc 文件数据连接到存储过程

php - 选择、计数和显示(按组?)

php - 分组和排序问题

sql - 如何在 MySQL 中进行连续分组?