比较两个与postgresql的关系

时间:2015-08-12 11:47:05

标签: sql postgresql aggregate

我希望通过它的联接表比较两个条目并返回匹配百分比

联接表如下:

|recipe_id|ingredient_id|
|---------|-------------|
|    1    |      1      |
|    1    |      2      |
|    1    |      3      |
|-----------------------|
|    2    |      4      |
|    2    |      10     |
|    2    |      20     |
|-----------------------|

如果我提供ingredient_id =>的数组[1,2,3],预期结果为

|recipe_id|match_percent|
|---------|-------------|
|    1    |      100    |
|-----------------------|
|    2    |      0      |
|-----------------------|

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

我的建议是将数组作为查找表并与之连接以查找计数

select t.recipe_id, 
count(t.ingredient_id)/(select count(*) from lookup_table)*100 as match_percent 
from
(
select t1.recipe_id,t1.ingredient_id from table as t1 inner join lookup_table as t2
on t1.ingredient_id=t2.ingredient_id
) as t 
group by t1.recipe_id