Snowflake - 连接两个 table,其中一个 table 的 ID 由分号分隔

Snowflake - Joining two tables where one table's IDs are delimited by a semicolon

我在 Snowflake 中工作,给定 table 和列中的一些 ID 由分号分隔。尽管有这个分隔符,tables 仍然应该被加入。任何加入 table 的尝试通常都会遇到某种错误。

下面是我尝试执行的示例。

       table_A                       table_B
+----------+----------+      +----------+----------+ 
| some_id  |  F_Name  |      | some_id  |  L_Name  |
+----------+----------+      +----------+----------+
|   12345  |   John   |      |12345;4321|    Doe   |
+----------+----------+      +----------+----------+

Attempted SQL Statement

select table_A.some_id, table_A.F_name, table_B.L_Name
from table_A
left join table_B on table_A.some_id like '%'||table_B.some_id||'%'

此特定问题的来源已在此处显示,但似乎不起作用。可能无法以这种特定方式进行连接。 https://community.snowflake.com/s/question/0D50Z00008zPLLx/join-with-partial-string-match

非常感谢任何帮助。

您的方法是正确的,但您对 LIKE 子句的使用不正确。您正在寻找 table_A.some_id 作为 table_B.some_id

的一部分

所以您的查询应该是:

WITH table_A AS (
  SELECT '12345' AS some_id, 'John' AS F_NAME
),
table_B AS (
  SELECT '12345;4321' AS some_id, 'Doe' AS L_NAME
)
SELECT 
    table_A.some_id, 
    table_A.F_name, 
    L_Name
FROM table_A
LEFT JOIN table_B 
    ON table_B.some_id LIKE '%'||table_A.some_id||'%'
;

如果您使用 CTE 来展平第二个 table,然后过滤掉重复项

WITH expand AS (
    SELECT 
       f.seq as seq,
       f.index as index
       f.value as join_token
       t.l_name
    FROM table_b t,
      lateral split_to_table(t.some_id, ';') f
)
SELECT 
  a.some_id, 
  a.f_name, 
  f.l_name
FROM table_a AS a
LEFT JOIN expand AS f
    ON a.some_id = f.join_token
QUALIFY row_number() over (partition by f.seq ORDER BY f.index) == 1