2013-01-17 78 views
0

我需要計算城市列中每個獨特的動物。MySQL:獲得一列中不同字段值的計數

下面是我想查詢:
SELECT city, animals, COUNT(animals) AS count_animals FROM city_animals GROUP BY city

這顯然是行不通的,這是給類似的結果...

City   Animals count_animals 
---------  ---  -- 
Arlington  Cow  1 
Austin   Cat  2 
Bastrop   Cow  2 
Big Sandy  Horse 2 
Cedar Creek  Horse 2 
Cedar Hill  Cow  2 
Chandler  Horse 1 
Decatur   Dog  1 

我正在尋找這樣的事情:

City   Animals count_animals 
---------  ---  -- 
Arlington  Cow  1 
Austin   Cat  2 
Bastrop   Cow  2 
Big Sandy  Horse 2 
*Cedar Creek Horse 1* 
*Cedar Creek Lizard 1* 
*Cedar Hill  Cow  1* 
*Cedar Hill  Horse 1* 
Chandler  Horse 1 
Decatur   Dog  1 

下面是我修改的數據:

City   Animals 
-----   -------- 
Arlington  Cow 
Austin   Cat 
Austin   Cat 
Bastrop   Cow 
Bastrop   Cow 
Big Sandy  Horse 
Big Sandy  Horse 
Cedar Creek  Horse 
Cedar Creek  Lizard 
Cedar Hill  Cow 
Cedar Hill  Horse 
Chandler  Horse 
Decatur   Dog 
DeSoto   Cow 
DeSoto   Horse 
DeSoto   Cow 
Duncanville  Llama 
Duncanville  Cow 
Farmers Branch Cat 
Farmers Branch Dog 
Garland   Lizard 
Garland   Cow 
Garland   Cow 
Garland   Lizard 
Garland   Cow 
georgetown  Llama 
Gladewater  Horse 
Hurst   Horse 
Kempv   Llama 
Mckinney  Dog 
Mckinney  Dog 
Mckinney  Dog 
Midlothian  Horse 
Midlothian  Horse 
Ovilla   Horse 
Ovilla   Horse 
Palestine  Horse 
Palestine  Horse 
Porter   Horse 
Porter   Cow 
Rockwall  Cow 
SPRING   Dog 
SPRING   Dog 
Terrell   Cow 
+0

否「阿倫,德州「? :) –

回答

3

如果你想爲每個animal計數,那麼你將要GROUP BY城市和動物:

SELECT city, 
    animals, 
    COUNT(animals) AS count_animals 
FROM city_animals 
GROUP BY city, animals 

SQL Fiddle with Demo

結果:

|   CITY | ANIMALS | COUNT_ANIMALS | 
-------------------------------------------- 
|  Arlington |  Cow |    1 | 
|   Austin |  Cat |    2 | 
|  Bastrop |  Cow |    2 | 
|  Big Sandy | Horse |    2 | 
| Cedar Creek | Horse |    1 | 
| Cedar Creek | Lizard |    1 | 
|  Cedar Hill |  Cow |    1 | 
|  Cedar Hill | Horse |    1 | 
|  Chandler | Horse |    1 | 
|  Decatur |  Dog |    1 | 
+0

賈!謝謝你,你是男人! (: – Tim

+0

@TimBolton樂於幫助。:) – Taryn

相關問題