Join to splitted string columns in Oracle

后端 未结 3 976
南笙
南笙 2021-01-28 06:40

I have a column in our database that holds 4 fields as a \"\\\" delimited string.

I have split the fields as I need them seperatly in my report.

I also need to

相关标签:
3条回答
  • 2021-01-28 07:26

    I think this is the query you want:

    select gch.Line, gch.productB, gch.productC,
           REGEXP_SUBSTR(p.delimited, '[^\]+', 1, 4)
    from  products p inner join
          lineitems gch 
          on gch.Line = REGEXP_SUBSTR(p.delimited, '[^\]+', 1, 1) and
             gch.productB = REGEXP_SUBSTR(p.delimited, '[^\]+', 1, 2) and
             gch.productC = REGEXP_SUBSTR(p.delimited, '[^\]+', 1, 3)
    where p.productid = 1;
    

    You need neither a subquery nor a temporary table.

    0 讨论(0)
  • 2021-01-28 07:30

    You can use CTE as follows.

    with pfcc as 
    (select REGEXP_SUBSTR(delimited , '[^\]+', 1, 1) colA,
           REGEXP_SUBSTR(delimited , '[^\]+', 1, 2) colB,
           REGEXP_SUBSTR(delimited , '[^\]+', 1, 3) colC,
           REGEXP_SUBSTR(delimited , '[^\]+', 1, 4) colD
      from products
     where productid = 1)
    select * from pfcc tmp
    inner join lineitems gch 
        on gch.Line = tmp.colA
        AND gch.productB = tmp.colB
        AND gch.productC = tmp.colC;
    
    0 讨论(0)
  • 2021-01-28 07:39

    WARNING! The regular expression '[^\]+' will return unexpected results if there is a null item in the list and you are selecting the element after that null item. See this example where the 3rd item is selected, but '4' is returned. '4' is really the 4th item in the delimited list, not the third. Indeed it is the 3rd item where there is a value though.

    SQL> select REGEXP_SUBSTR('1\\3\4', '[^\]+', 1, 3) colA from dual;
    
    C
    -
    4
    
    SQL>
    

    Use this instead, where the actual 3rd item in the list is selected:

    SQL> select REGEXP_SUBSTR('1\\3\4', '([^\]*)(\\|$)', 1, 3, NULL, 1) colA from dual;
    
    C
    -
    3
    

    See this post for a more detailed example and explanation: REGEX to select nth value from a list, allowing for nulls

    0 讨论(0)
提交回复
热议问题