【问题标题】:Search and extract data from SQL column having some delimiter从具有某些分隔符的 SQL 列中搜索和提取数据
【发布时间】:2016-02-05 11:35:10
【问题描述】:

我在表格中有一列包含以下格式的数据:

(DeliveryMethod+NON;Installation_Method+NoInstallation;Services_Reference_ID+100118547,44444,33333;Service_ID+2222)

(key+value;key+value;key+value;key+value;key+value;key+value;key+value;)

我想根据特定的"key" 和"key+value" 可以在任何位置从该列中搜索和提取特定的"value",如何使用SQL 查询来做到这一点?

【问题讨论】:

    标签: sql search extract regexp-substr


    【解决方案1】:

    正如我在这篇文章中回答的那样,这是在 Oracle 中处理它的一种方法:Oracle 11gR2: split string with multiple delimiters(add)。希望您可以将逻辑应用于您的 RDBMS。请注意,此答案不仅从字符串中获取值,还尝试解析字符串并返回值,以便可以像查询结果集中的行一样处理它们。对于您的场景,这可能有点矫枉过正。无论如何,这只是看待它的一种方式。

    -- Original data with multiple delimiters and a NULL element for testing.
    with orig_data(str) as (
      select 'DeliveryMethod+NON;Installation_Method+NoInstallation;;Services_Reference_ID+100118547,44444,33333;Service_ID+2222' from dual 
    ),
    --Split on first delimiter (semi-colon)
    Parsed_data(rec) as (
      select regexp_substr(str, '(.*?)(;|$)', 1, LEVEL, NULL, 1)
      from orig_data
      CONNECT BY LEVEL <= REGEXP_COUNT(str, ';') + 1 
    )
    -- For testing-shows records based on 1st level delimiter
    --select rec from parsed_data;
    
    -- Split the record into columns
    select regexp_replace(rec, '^(.*)\+.*', '\1') col1,
           regexp_replace(rec, '^.*\+(.*)', '\1') col2
    from Parsed_data;
    

    结果:

    为了具体回答您的问题,为了获取基于键的值,请将最后一个查询更改为此以获取键为“Service_ID”的值:

    select value
    from (
       select regexp_replace(rec, '^(.*)\+.*', '\1') key,
              regexp_replace(rec, '^.*\+(.*)', '\1') value
       from Parsed_data )
    where key = 'Service_ID';
    

    结果:

    或者使用正则表达式将其从字符串中提取出来:

    with orig_data(str) as (
      select 'Service_ID+2222;DeliveryMethod+NON;Installation_Method+NoInstallation;;Services_Reference_ID+100118547,44444,33333' from dual 
    )
    select regexp_substr(str, '(.*?)Service_ID\+(.+?)(;|$)', 1, 1, NULL, 2) value
    from orig_data; 
    

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 2019-08-06
      • 2022-01-13
      • 1970-01-01
      • 2021-08-21
      • 2017-09-12
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多