0

都市の列にあるそれぞれのユニークな動物を数える必要があります。

これが私が試しているクエリです:
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
4

1 に答える 1

3

それぞれのカウントが必要な場合は、都市と動物の両方animalが必要になります。GROUP BY

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

SQL FiddlewithDemoを参照してください

結果:

|           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 |
于 2013-01-17T20:28:22.900 に答える