2013-05-20 85 views
1

我實際上面臨着MySQL的一個問題,我需要具有類似的GROUP BY行爲,但不需要分組。根據條件計算行數(類似於組)

以下是僅有一個名爲'resident'的表的示例,其中包含兩列:'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

,你可以將它與下面的查詢:

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` 

這提取每個城市的居民在一個子查詢的金額,然後加入本品具有非常表的名稱。

+0

謝謝,工作也是如此。 – zakiz

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

謝謝,它的工作! – zakiz