[英]How can I get several counts of a column in one SQL query?
I have a schema like: 我有一个架构,如:
PetOwner:
owner_id | first_name | last_name
---------------------------------
1 | john | smith
2 | jane | doe
3 | jack | jones
Pets:
pet_id | owner_id | name | type
-------------------------------
1 | 1 | a | dog
2 | 1 | b | dog
3 | 1 | c | dog
4 | 1 | d | cat
5 | 1 | e | cat
6 | 1 | f | fish
7 | 2 | g | dog
8 | 2 | h | dog
9 | 2 | i | fish
10 | 3 | j | dog
And I'd like to write a query that gives me: 我想写一个给我的查询:
first_name | last_name | dog_count | cat_count | fish_count
-----------------------------------------------------------
john | smith | 3 | 2 | 1
jane | doe | 2 | 0 | 1
jack | jones | 1 | 0 | 0
There is a known set of pet types, so this doesn't need to make a column for arbitrary types. 有一组已知的宠物类型,因此不需要为任意类型创建列。 In addition, any owners that don't have a certain type of pet should get a 0 count for that pet type. 此外,任何没有某种宠物类型的所有者都应该获得该宠物类型的0计数。
I've already tried a query like: 我已经尝试过如下查询:
SELECT first_name, last_name, owner_id, type, COUNT(*)
FROM Pets, PetsOwner
GROUP_BY owner_id, type
which yields: 产量:
first_name | last_name | owner_id | type | COUNT(*)
---------------------------------------------------
john | smith | 1 | dog | 3
john | smith | 1 | cat | 2
john | smith | 1 | fish | 1
jane | doe | 2 | dog | 2
jane | doe | 2 | fish | 1
jack | jones | 3 | dog | 1
But this requires iterating over the result set to get the output I'm looking for, obviously something to avoid with SQL. 但是这需要迭代结果集来获取我正在寻找的输出,显然要避免使用SQL。 Also it doesn't provide the default 0 value for pet types that are absent from the table. 此外,它不提供表中不存在的宠物类型的默认值0。
Is it possible to do this with one SQL query? 是否可以使用一个SQL查询执行此操作? If not, is there a query I could do that is better (ie easier to work with) than the query I've found? 如果没有,是否有我可以做的查询比我找到的查询更好(即更容易使用)?
It's a MySQL database, if that makes a difference. 这是一个MySQL数据库,如果这有所作为。
Thanks for the help. 谢谢您的帮助。
Use SUM instead of COUNT: 使用SUM而不是COUNT:
SELECT o.first_name, o.last_name,
SUM(CASE WHEN p.type = 'cat' THEN 1 ELSE 0 END) as cat_count,
SUM(CASE WHEN p.type = 'dog' THEN 1 ELSE 0 END) as dog_count,
SUM(CASE WHEN p.type = 'fish' THEN 1 ELSE 0 END) as fish_count
FROM PetOwners o
JOIN Pets p ON o.id = p.owner_id
GROUP BY o.id
And if you want to include owners that don't have any pets at all, change JOIN
to LEFT JOIN
. 如果您想要包含完全没有宠物的所有者,请将JOIN
更改为LEFT JOIN
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.