【问题标题】:How to split two strings separated by a ; in two new columns如何拆分由 ; 分隔的两个字符串在两个新专栏中
【发布时间】:2022-12-01 10:46:56
【问题描述】:

所以我有一个命令,例如

SELECT something, string_agg(other, ';') FROM table
GROUP BY something HAVING COUNT(*)>1;

但我不知道如何将两列分开,因为它没有将 string_agg 视为一列。

这是我的原创

something | other |         
--------+--------+
 example  | yes, no   |  
 using  | why, what  |  

我想要这个

something | other | new        
--------+--------+------
 example  | yes   | no     
 using  | why     | what    

【问题讨论】:

    标签: postgresql split


    【解决方案1】:

    我们可以在这里使用正则表达式:

    SELECT
        something,
        SUBSTRING(other FROM '[^,]+') AS other,
        REGEXP_REPLACE(other, '.*,[ ]*', '') AS new
    FROM yourTable;
    

    【讨论】:

      【解决方案2】:

      我会把它聚合成一个数组:

      select something, 
             others[1] as other, 
             others[2] as "new"
      from (
        SELECT something, array_agg(other) as others
        FROM table
        GROUP BY something 
        HAVING COUNT(*)>1
      ) x
      

      【讨论】:

        【解决方案3】:

        备选方案:只需使用split_part() 功能。我结合 trim() 函数来删除前导/尾随空格。 (见demo

        select something
             , trim(split_part(other, ',', 1)) other
             , trim(split_part(other, ',', 2)) new 
          from table;
        

        【讨论】:

          猜你喜欢
          • 2018-01-06
          • 2020-04-11
          • 2012-11-15
          • 2016-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多