识别字符串中子字符串的最后一次出现,其中子字符串来自 table。天睿数据

Identify the last occurance of a subsring in a string, where the substring is from a table. Teradata

我遇到以下问题:

我需要确定 table A 中给定的任何子字符串的最后一次出现,以及 return 在 select 语句中 return 中给定的值另一个声明。这有点令人费解,但这是代码:

SELECT TRIM(COUNTRY_CODE)
FROM (
    SELECT TOP 1 POSITION( PHRASE IN MY_STRING) AS PHRASE_LOCATION, CODE 
    FROM REFERENCE_TABLE -- Where the country list is located
    WHERE PHRASE_LOCATION > 0 -- To return NULL if there is no matches
    ORDER BY 1 DESC -- To get the last one 
    ) t1

这在 运行 单独运行时有效,但我很难让它作为另一个查询的一部分运行 select。我需要 "MY_STRING" 来自更高级别的嵌套 select 三层。这样做的原因是系统是如何在更高层次上设计的。

换句话说,我需要以下内容:

到目前为止,我已经尝试了您在上面看到的内容,但是由于系统的限制,我无法发挥创意。

Example Phrases: "New York", "London", "Oslo"
Example Codes: "US", "UK, "NO"
Example Strings: "London House, Something street, New York"; "Some street x, 0120, OSL0". 
Desired Outcomes: "US"; "NO"

这将导致 产品连接,即使用大量 CPU:

SELECT MY_STRING
  -- using INSTR searching the last occurance instead of POSITION if the same PHRASE might occur multiple times
  -- INSTR is case sensitive -> must use LOWER 
  ,Instr(Lower(MY_STRING), Lower(PHRASE), -1, 1) AS PHRASE_LOCATION
  ,CODE 
  ,PHRASE
FROM table_with_MY_STRING
LEFT JOIN REFERENCE_TABLE -- to return NULL if no match
ON PHRASE_LOCATION > 0
QUALIFY
   Row_Number() -- return last match
   Over (PARTITION BY MY_STRING
         ORDER BY PHRASE_LOCATION DESC) = 1

如果这不够有效,另一种可能的解决方案可能会利用 STRTOK_SPLIT_TO_TABLE/REGEXP_SPLIT_TO_TABLE:将地址拆分成多个部分,然后将这些部分连接到 PHRASE。