使用Postgresql提取第二个找到的匹配子字符串

时间:2016-12-08 05:27:42

标签: sql regex postgresql substring

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

问题是,它只会将第一个值匹配到regex SUBSTRING -$4,000.00SUBSTRING是否有传递给-$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

期望的结果:

{{1}}

1 个答案:

答案 0 :(得分:0)

试试这个

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