【问题标题】:Pivoting a column based on sort order but with same name in PostgreSQL基于排序顺序但在 PostgreSQL 中具有相同名称的列
【发布时间】:2020-10-15 04:22:08
【问题描述】:

我有一个 CTE,我在其中获取如下详细信息。我希望根据位置旋转此结果。但列名必须相同(如果不是可以不同)。

下面给出了示例输出,任何人都可以对此提出建议或帮助吗?

PostgreSQL 版本 11

表有近 2000 个 ID 和多达 10 个链接。 示例输入:

   ID              LINK                                Position
    757 "https://www.shop.com/product/5/_/5_142_40.jpg" 4
    757 "https://www.shop.com/product/3/_/3_347_44.jpg" 2
    757 "https://www.shop.com/product/4/_/4_207_43.jpg" 3
    757 "https://www.shop.com/product/2/_/2_416_44.jpg" 1
    758 "https://www.shop.com/product/5/_/5_142_39.jpg" 4
    758 "https://www.shop.com/product/4/_/4_207_42.jpg" 3
    758 "https://www.shop.com/product/3/_/3_347_43.jpg" 2
    758 "https://www.shop.com/product/2/_/2_416_43.jpg" 1
    760 "https://www.shop.com/product/5/_/5_142_42.jpg" 4

示例输出:

ID   link                      link                link                link
757 .../2/_/2_416_44.jpg   ../3/_/3_347_44.jpg  ../4/_/4_207_43.jpg  ../5/_/5_142_40.jpg
758 .../2/_/2_416_43.jpg   ../3/_/3_347_43.jpg  ../4/_/4_207_42.jpg. ../5/_/5_142_39.jpg
760 ../5/_/5_142_42.jpg

【问题讨论】:

    标签: sql postgresql select pivot window-functions


    【解决方案1】:

    您可以使用row_number() 和条件聚合。但是,列名需要不同:

    with mycte as (...) -- your cte here
    select
        id,
        max(link) filter(where rn = 1) link1,
        max(link) filter(where rn = 2) link2,
        max(link) filter(where rn = 3) link3,
        max(link) filter(where rn = 4) link4
    from (
        select c.*, row_number() over(partition by id order by position) rn
        from mycte c
    ) t
    group by id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多