postgres 聚合几个表

postgres aggregration over a few tables

我有以下表格:

targeting
-- id
-- type
-- value

performance
-- id
-- ad_name
-- installs

performance_targeting
-- id
-- performance_id
-- targeting_id

我想获取每个效果的目标值。

为了实现它,我写道:

select performance_id, string_agg(value, ',' order by value) as values from 
targeting join performance_targeting
on targeting.id = performance_targeting.id
group by performance_id

但是结果不正确。

参见 sqlfiddle - 如您所见,id 为 1 的效果与定位 18-24 岁和女性相关。我希望 array_agg 显示以下内容:

performance_id   targeting_values 
1                18-24,female
2                25-34,male
3                18-24,female
4                25-34,female

怎么了?

你有一个小错误。你有 performance_targeting.id 而不是 performance_targeting.targeting_id

select performance_id, 
   string_agg(value, ', ' ORDER BY value) as values 
from targeting 
join performance_targeting on targeting.id = performance_targeting.targeting_id
group by performance_id

demo