• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

PostgreSQL和amp;amp;regexp_split_to_array +嵌套

用户头像
it1352
帮助1

问题说明

我有这样的字符串

测试1 |纽约|X,测试2 |芝加哥| Y,测试3 |宾夕法尼亚州哈里斯堡|Z

Test 1|new york| X, Test 2| chicago|Y, Test 3| harrisburg, pa| Z

我需要的结果是

 Column1  Column 2     Column3
 Test 1   new york        X
 Test 2   chicago         Y
 Test 3   harrisburg,pa   Z

但是运行此查询

SELECT  
split_part(stat.st, '|', 1) Column1,
split_part(stat.st, '|', 2) Column2,    
split_part(stat.st, '|', 3) Column3
FROM
(
    SELECT
            UNNEST (
                string_to_array('Test 1|new york| X, Test 2| chicago|Y, Test 3| harrisburg, pa| Z',',')
            )
         AS st
) stat;

结果是

 Column1  Column 2   Column3
 Test 1   new york      X
 Test 2   chicago       Y
 Test 3   harrisburg    
 pa          Z  

Column3可以是所有内容(|除外).可能与之匹配的模式.可以重复N次.除|外,STRING可能是所有内容字符

Column3 could be everything (except | ). Possible pattern to match it's .This could be repeated N times. STRING could be everything except | char.

如何使用 regexp_split_to_array()设置我想要的结果?

How could I use regexp_split_to_array() to have my desire result set?

正确答案

#1

有足够的信息使这些工作正常进行.但这可以完成工作:

There is barely enough information to make this work. But this does the job:

SELECT * FROM crosstab3(
   $$
   SELECT (rn/3)::text AS x, (rn%3)::text, item
   FROM  (
      SELECT row_number() OVER () - 1 AS rn, trim(item) AS item
      FROM (
         SELECT CASE WHEN rn%2 = 1 THEN regexp_split_to_table(item, ',') 
                     ELSE item END AS item
         FROM  (
            SELECT row_number() OVER () AS rn, *
            FROM regexp_split_to_table('Test 1|new york| X, Test 2| chicago|Y, Test 3| harrisburg, pa| Z', '\|') AS item
            ) x
         ) y
      ) z
   $$)

返回:

 row_name | category_1 |   category_2   | category_3
---------- ------------ ---------------- ------------
 0        | Test 1     | new york       | X
 1        | Test 2     | chicago        | Y
 2        | Test 3     | harrisburg, pa | Z

| 处分割字符串后,我基于这样的标准:只有行号不均匀的行应在处分割.
我对结果进行 trim()并添加另一个 row_number()的导数,以在进行交叉制表之前达到此中间状态:

After splitting the string at |, I build on the criterion that only lines with uneven row number shall be split at ,.
I trim() the results and add derivatives of another row_number() to arrive at this intermediary state before doing the cross tabulation:

 x | text |      item
--- ------ ----------------
 0 | 0    | Test 1
 0 | 1    | new york
 0 | 2    | X
 1 | 0    | Test 2
 1 | 1    | chicago
 1 | 2    | Y
 2 | 0    | Test 3
 2 | 1    | harrisburg, pa
 2 | 2    | Z

最后,我从查看全文

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfjagi
系列文章
更多 icon
同类精品
更多 icon
继续加载