问题描述
我正在尝试编写一个使用3个表的postgres查询:people,attribute和people_attribute联接
人物表:
id,name
属性表:
id,name,attr_group
people_attribute加入:
people_id,attribute_id
所需的输出:
name | fav_colors | fav_music | fav_foods
-----------------------------------------------------------------
michael | red,blue,green | pop,hip-hop,jazz | pizza,burgers,tacos
bob | orange,green | null | tacos,steak,fish
...等
每个attr_group的标签范围从无到〜12
这是我正在使用的查询:
select
p.id,p.name,(case when a.attr_group like 'fav_colors' then string_agg(a.name,',') else null end) as fav_colors,(case when a.attr_group like 'fav_music' then string_agg(a.name,') else null end) as fav_music,(case when a.attr_group like 'fav_foods' then string_agg(a.name,') else null end) as fav_foods,from people as p
join people_attribute as pa on pa.people_id = p.id
join "attribute" as a on a.id = pa.attribute_id
group by 1,2,a.attr_group
order by 1 asc;
返回:
name | fav_colors | fav_music | fav_foods
-----------------------------------------------------------------
michael | red,green | null | null
michael | null | pop,jazz | null
michael | null | null | pizza,tacos
bob | null | null | null
bob | orange,green | null | null
bob | null | null | tacos,fish
我感觉自己接近了,但是不确定如何将其展平以实现所需的输出,如上所示。任何帮助将不胜感激!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)