我是PostgreSQL的新手。我的目标是运行一个查询,该查询返回为每个proposal_id列出的所有item_id,其中每个唯一的proposal_id是一个单独的行条目,每个item_id是该行条目中的一列。
表1的数据如下所示:
proposal_id item_id
1 83054
1 81048
2 71384
2 24282
2 19847
2 18482
3 84720
4 18081
4 73018
这是我想要的样子:
proposal_id item_id_1 item_id_2 item_id_3 item_id_4 item_id_n
1 83054 81048
2 71384 24282 19847 18482
3 84720
4 18081 73018
面临的挑战是,我可以为1到11个或更多条目之间的任何地方使用相同的proposal_id。
为了提出这个问题,这是简化版本。一旦确定了这一点,我的计划就是将此处其他表中每个item_id和proposal_id的其他数据结合在一起。
任何帮助,不胜感激。
谢谢!
编辑:固定表美学
首先,确定需要多少列:
select proposal_id, array_length(array_agg(item_id), 1)
from the_table
group by 1
order by 2 desc
limit 1
接下来,使用足够数量的a执行以下查询。
select proposal_id, a[1] id1, a[2] id2, a[3] id3, a[4] id4
from (
select proposal_id, array_agg(item_id) a
from the_table
group by 1
order by 1) z
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句