简体   繁体   English

基于foreign_key的百分比

[英]Percentage based on foreign_key

I have a table called animals that have the following columns:我有一个名为animals的表,它具有以下列:

id: INT
state: VARCHAR

And another table called houses that have the following columns:另一个名为房屋的表具有以下列:

id: INT
animal_id: INT
color: VARCHAR

I am trying to get the percentage of animals (which state is 'living') and its ids are within a given set, that have at least a house (which color is 'red').我试图获得动物的百分比(哪个状态是“活着”)并且它的 id 在给定的集合内,至少有一个房子(哪个颜色是“红色”)。 If one animal has more than one red house, it doesn't matter, it should just be counted once.如果一只动物有不止一个红房子,也没关系,应该只算一次。

I know how to get the number of animals with those conditions:我知道如何获得具有这些条件的动物数量:

SELECT COUNT(*)
FROM animals
WHERE state = 'living'
AND id IN (10,11,12)

And I know how to get the houses with those conditions:我知道如何获得符合这些条件的房屋:

SELECT COUNT(*)
FROM houses
WHERE color = 'red'

I am not exactly sure how to combine both queries to get a percentage of animals.我不确定如何结合两个查询来获得动物的百分比。

Sample data:样本数据:

animals (id, state)

1, 'living'
2, 'dead'
3, 'living'
4, 'living'
5, 'dead'
6, 'living'


houses (id, animal_id, color)

1, 1, 'red'
2, 2, 'red'
3, 1, 'blue'
4, 6, 'red'
5, 4, 'red'
6, 1, 'red'  

And we want to scope down the animals to just the ones with ids 1, 2, 3 and 5.我们希望将动物范围缩小到只有 ID 为 1、2、3 和 5 的动物。

So, since the animals with ids 2 and 5 are dead, they should not be counted as part of the denominator.因此,由于 id 为 2 和 5 的动物已经死亡,因此不应将它们计入分母。 Now, this leaves us with animals 1 and 3, but just animal with id 1 has at least one red house (notice that it has two, but we don't care), which means that the percentage is:现在,这给我们留下了动物 1 和 3,但只有 id 为 1 的动物至少有一个红房子(注意它有两个,但我们不在乎),这意味着百分比是:

(1 animal with at least one read house) / (2 animals that are living) = 50% (1 只动物至少有一个阅读屋)/(2 只活着的动物)= 50%

You can use a LEFT JOIN to combine the tables.您可以使用LEFT JOIN来组合表。 Then AVG() can be used to get the ratio you want:然后AVG()可用于获得您想要的比率:

SELECT AVG( (h.color = 'red')::int ) as ratio_red
FROM animals a LEFT JOIN
     houses h
     ON a.id = h.animal_id
WHERE a.state = 'living'
      a.id IN (10, 11, 12);

For the revised calculation, you can use:对于修改后的计算,您可以使用:

SELECT COUNT(DISTINCT CASE WHEN h.color = 'red' THEN h.animal_id END) / COUNT(DISTINCT a.id) as ratio_red
FROM animals a LEFT JOIN
     houses h
     ON a.id = h.animal_id
WHERE a.state = 'living'
      a.id IN (10, 11, 12);

选择animal_id,color ,living from house t1 Inner join(select Id,count(*) as living from animal group by id) t2 On t1.animalid=t2.id where color='red'

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

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