簡體   English   中英

MySQL:獲取列中不同字段的值

[英]MySQL: Get count on values of different fields in a column

我需要在“城市”列上對每種獨特的動物進行計數。

這是我正在嘗試的查詢:
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

如果您想要每種animal的數量,那么您將GROUP BY城市和動物分組:

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

參見帶有演示的SQL Fiddle

結果:

|           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 |

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM