【问题标题】:How to split the row by a comma and unpivot the table in PostgreSQL?如何用逗号分割行并在 PostgreSQL 中取消透视表?
【发布时间】:2022-01-23 20:58:30
【问题描述】:

我有这张表,我想用逗号分隔列并取消透视它

我的桌子

+------------+-------------------+---------------------------+
|birthday_id | child_birthday_id | place                     | 
+------------+------------------ +---------------------------+
|  1         |        9          |  Minsk, Mogilev, Polotsk  | 
+-------+----------+-------------+---------------------------+

我想要 3 行不同的地方

+------------+-------------------+----------------------+
|birthday_id | child_birthday_id | place                | 
+------------+------------------ +----------------------+
|  1         |        9          |  Mogilev             |
|  1         |        9          |  Minsk               | 
|  1         |        9          |  Polotsk             | 
+-------+----------+-------------+----------------------+

我知道如何在 MSSQLS 服务器中使用 CROSS APPLY 但在 Postgres IDK 中使用

SELECT 
    birthday_id , 
    child_birthday_id,
    place
FROM 
    sh.test
    CROSS APPLY STRING_SPLIT(place, ',');

【问题讨论】:

  • Edit 问题并展示您已经尝试过的内容。解释失败的原因/位置。具体(错误消息、意外结果等)。

标签: sql postgresql split


【解决方案1】:

SQL Server 的 CROSS APPLY 在 Postgres 中转换为 CROSS JOIN LATERAL。要将字符串拆分成表格,可以使用regexp_split_to_table()

SELECT t.birthday_id,
       t.child_birthday_id,
       p.place
       FROM sh.test AS t
            CROSS JOIN LATERAL regexp_split_to_table(t.place, '\s*,\s*') AS p
                                                                            (place);

【讨论】:

    【解决方案2】:

    您可以使用string_to_array()unnest()

    SELECT t.birthday_id , 
           t.child_birthday_id,
           p.place
    FROM sh.test t
      CROSS JOIN LATERAL unnest(string_to_array(place, ',')) as p(place);
    

    如果您使用的是 Postgres 14,您也可以使用 string_to_table(t.place, ',')

    【讨论】:

    • 您需要CROSS JOIN LATERAL 吗?你能不能不干脆SELECT birthday_id, child_id, unnest(string_to_array(place, ', ')) as place FROM demo GROUP BY 1, 2;
    • @JonathanWillcock:不,你真的不需要它。但我更喜欢在进行交叉连接时明确表达
    猜你喜欢
    • 2014-10-26
    • 2022-03-18
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2018-08-11
    相关资源
    最近更新 更多