Please help me a study case bellow: I have a table in Postgres:
and how to create a view or Table B from Table A like this:
I try to use crosstab but it's not working.
Thank you so much!
Please help me a study case bellow: I have a table in Postgres:
and how to create a view or Table B from Table A like this:
I try to use crosstab but it's not working.
Thank you so much!
You can use row_number()
and conditional aggregation:
select item_id,
max(author) filter (where seqnum = 1) as author_1,
max(author) filter (where seqnum = 2) as author_2,
max(author) filter (where seqnum = 3) as author_3,
max(author) filter (where seqnum = 4) as author_4
from (select a.*,
row_number() over (partition by item_id order by author) as seqnum
from tablea a
) a
group by item_id;
I would aggregate the authors into an array, then select the array elements in an outer query:
select item_id,
authors[1] as author_1,
authors[2] as author_2,
authors[3] as author_3
from (
select item_id,
array_agg(author order by author) as authors
from items
group by item_id
) t;