[英]how to display table records who has one record when another table who is joined has many records
[英]SQL - Counting how many associated records another table has
由于我是 SQL 初学者,我无法用简单的方式描述问题,所以让我向您展示一个示例:
3 表:
产品
团体
人
如您所见,GROUP 可以有多个 PERSON,而 PRODUCT 可以与 GROUP 和 PERSON 连接。
从这一点来看,我想计算一个 GROUP 中拥有 PRODUCT 的人数
我不太了解 IN 的背景或在 FROM 中使用另一个 SELECT,所以如果这就是重点,那么我很高兴我领先一步,哈哈。
SELECT
group.name as GROUP_name,
COUNT(DISTINCT person_id) AS PERSON_having_min_one_PRODUCT
FROM products
LEFT JOIN groups ON groups.id = products.group_id
LEFT JOIN persons ON persons.id = products.person_id;
有了这个数据:
GROUP
ExampleGroupName1 has 3 PERSONs, but 2 of them has >0 PRODUCTS
ExampleGroupName2 has 3 PERSONs and all of them has >0 PRODUCTS
ExampleGroupName3 has 2 PERSONs, but none of them has the PRODUCT
ExampleGroupName4 has 2 PERSONs, but only 1 has >0 PRODUCT
我想要这样的输出:
GROUP_name | PERSON_having_min_one_PRODUCT
ExampleGroupName1 | 2
ExampleGroupName2 | 3
ExampleGroupName4 | 1
我想计算一个组内拥有产品的人数
注意:我将假设表product
没有列group_id
,因为它是多余的并且会导致很多错误。
以下查询将通过加入表person
和product
向您显示您想要的结果:
select
count(distinct x.id)
from person x
join product p on p.person_id = x.id
where x.group_id = 123 -- choosing a specific group
and p.id = 456 -- choosing a specific product
这宁愿像下面那样简单,这意味着所有具有某些group_id
和count(persons)
以及那些通过在group_id
子句中使用的 id 拥有某些产品的计数
Select group_id,
count( distinct id ) AS "PERSON_WITH_PRODUCT"
from
person group by group_id having id
in (Select id from product);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.