【问题标题】:extract the second found matching substring using Postgresql使用 Postgresql 提取第二个找到的匹配子字符串
【发布时间】:2017-04-23 06:37:19
【问题描述】:

我使用以下查询从存储 JSON 对象的列中提取值。

它的问题是,它只会拉取与SUBSTRING 内的regex 匹配的第一个值,即-$4,000.00,是否有一个参数要传递给SUBSTRING 以拉取值-$1,990.00 为好在另一列。

SELECT attribute_actions_text
, SUBSTRING(attribute_actions_text FROM '"Member [Dd]iscount:":"(.+?)"') AS column_1
, '' AS column_2

FROM  (
   VALUES
     ('[{"Member Discount:":"-$4,000.00"},{"Member discount:":"-$1,990.00"}]')
   , (NULL)
   ) ls(attribute_actions_text)

想要的结果:

column_1        column_2  
-$4,000.00      -$1,990.00

【问题讨论】:

    标签: sql regex postgresql substring


    【解决方案1】:

    试试这个

    WITH data(id,attribute_actions_text) as (
      VALUES
          (1,'[{"Member Discount:":"-$4,000.00"},{"Member Discount:":"-$1,990.00"}]')
        , (2,'[{"Member Discount:":"-$4,200.00"},{"Member Discount:":"-$1,890.00"}]')
        , (3,NULL)
    ), match as (
      SELECT
        id,
        m,
        ROW_NUMBER()
        OVER (PARTITION BY id) AS r
      FROM data, regexp_matches(data.attribute_actions_text, '"Member [Dd]iscount:":"(.+?)"', 'g') AS m
    )
    SELECT
       id
      ,(select m from match where id = d.id AND r=1) as col1
      ,(select m from match where id = d.id AND r=2) as col2
      FROM data d 
    

    结果

    1,"{-$4,000.00}","{-$1,990.00}" 2,"{-$4,200.00}","{-$1,890.00}" 3,NULL,NULL

    【讨论】:

      猜你喜欢
      • 2015-10-19
      • 2017-01-26
      • 1970-01-01
      • 2015-08-30
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多