简体   繁体   English

SQL查询以计算对象中每个元素的数量

[英]SQL Query to count the number of each element in an object

I have a database table like this: 我有一个这样的数据库表:

Room Name     ||     Animal
----------------------------
Room1 || Cat
Room1 || Dog
Room1 || Dog
Room2 || Cat
Room2 || Cat
Room2 || Dog
Room2 || Dog

I want to read this table with a SQL query and as result I want to count the number of each animal in the room: 我想通过SQL查询读取此表,因此我想计算房间中每只动物的数量:

Room1: 1 cat 2 dog
Room2: 2 cats 2 dog

(The output format doesn't matter) (输出格式无关紧要)

Is there a SQL query that can help? 是否有可以帮助您的SQL查询? Or should I read the whole table and filter it programatically? 还是应该阅读整个表格并以编程方式对其进行过滤?

Thank you for any help 感谢您的任何帮助

SELECT [Room Name], [Animal], COUNT(*) FROM TableName GROUP BY [Room Name], [Animal]

This would return 这将返回

Room 1 | Cat | 1
Room 1 | Dog | 2
Room 2 | Cat | 2
Room 2 | Dog | 2
select room_name, animal, count(*)
from table 
group by room_name, animal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM