postgres聚合几个表

时间:2018-02-15 18:10:40

标签: sql postgresql string-aggregation

我有以下表格:

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

有什么问题?

1 个答案:

答案 0 :(得分:1)

你有一个小错误。您有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