在 PostgreSQL 中旋转 table

Rotate table in PostgreSQL

请帮我一个研究案例如下: 我在 Postgres 中有一个 table:

以及如何从 Table A 创建视图或 Table B,如下所示:

我尝试使用交叉表,但它不起作用。

Error

非常感谢!

您可以使用 row_number() 和条件聚合:

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;

我会将作者聚合到一个数组中,然后 select 外部查询中的数组元素:

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;