【问题标题】:Rotate table in PostgreSQL在 PostgreSQL 中旋转表
【发布时间】:2021-05-25 06:32:54
【问题描述】:

请帮我看看下面的案例: 我在 Postgres 中有一张桌子:

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

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

Error

非常感谢!

【问题讨论】:

  • 您需要对数据进行透视
  • 什么决定了作者的顺序?
  • 感谢您的提问,作者的顺序并不重要。可能第一个是author_1,第二个是author_2 ....
  • 当有 10000 位作者时,您期望的输出是什么?

标签: sql postgresql pivot


【解决方案1】:

我会将作者聚合成一个数组,然后在外部查询中选择数组元素:

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;

【讨论】:

    【解决方案2】:

    您可以使用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;
    

    【讨论】:

    • @TamNguyen 。 . .我注意到您不接受这个答案——这很好:OP 可以选择 OP 想要的任何答案。然而,一个数组将所有作者聚集在一起,如果某些项目有很多很多的作者,它可以使用更多的资源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多