根据标准计算行数(类似于分组)

时间:2013-05-20 12:47:08

标签: mysql

我实际上遇到了MySQL的一个问题,我需要有类似的GROUP BY行为,但没有分组。

以下是一个名为“resident”的表格的示例,其中包含2列:“name”,“city”。

如果我想计算每个城市的居民人数,我只需要这样做:

SELECT resident.city, count(resident.name) as 'Nb residents'
FROM resident
GROUP BY resident.city

结果如下:

| city | Nb residents |
| NY   |       3      |
| HK   |       1      |
| Rome |       2      |
...

但我正在寻找一种方法来显示我的结果:

|   name   |  city  |  Nb residents |
| Name1    | NY     |       3       |
| Name2    | NY     |       3       |
| Name3    | NY     |       3       |
| Name4    | HK     |       1       |
| Name5    | Rome   |       2       |
| Name6    | Rome   |       2       |

有可能吗?

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

SELECT resident.name, resident.city, (select count(a.name) from resident a where a.city = resident.city) as 'Nb residents'
FROM resident

答案 1 :(得分:2)

您可以使用以下查询进行此操作:

SELECT t1.`name`, t2.`city`, t3.`Nb residents`
FROM resident t1
JOIN ( SELECT resident.city, count(resident.name) as 'Nb residents' FROM resident GROUP BY resident.city ) t2
  ON t1.`city`= t2.`city`

这会在子查询中提取每个城市的居民数量,然后将其与该表格的名称联系起来。

相关问题