[英]Flatten count with one to many relationship
I have two tables, Person
and Hobby
, with a one to many relationship. 我有两个表,
Person
和Hobby
,具有一对多关系。
| ID | Person | | ID | PersonID | Hobby |
|----|--------| |----|----------|------------|
| 1 | Bob | | 1 | 1 | Skiing |
| 2 | Mike | | 2 | 2 | Biking |
| 3 | Frank | | 3 | 3 | Skiing |
| 4 | 1 | Numerology |
| 5 | 2 | Witchcraft |
| 6 | 3 | Stamps |
I want to produce a table that includes a single count for every person who likes Skiing or Stamps. 我想为每个喜欢滑雪或邮票的人制作一张只包含一个计数的表格。 Something like this:
像这样:
| Person | Count |
|--------|-------|
| Bob | 1 |
| Frank | 1 |
What would a working sql query look like? 一个有效的SQL查询是什么样的?
select p.person, count(p.id) as cnt
from person p join hobby h
on h.personid = p.id
where h.hobby = 'Skiing'
group by p.person
You have to join the tables and group by
the person id. 您必须加入表并按人员ID进行
group by
。
This solved it. 这解决了。 You need to count distinct
您需要数数不同
SELECT p.person, count(Distinct p.id) as Count
FROM person p join hobby h
ON h.personID = p.ID
WHERE h.hobby = 'Skiing'
OR h.hobby = 'Stamps'
GROUP BY p.ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.