oracle 查找最佳匹配

von4xj4u  于 2023-02-03  发布在  Oracle
关注(0)|答案(1)|浏览(162)

我试图从表T2中找到与表T3中的值最匹配的值。例如,这里我希望得到441作为结果。
请指示。
谢谢。

create table t3 (rc varchar2(20));
create table t2 (rcs varchar2(20));

insert into T3 values ('441449729804');
insert into T2 values ('44');
insert into T2 values ('441');
commit;
yfjy0ee7

yfjy0ee71#

如果只从t3中选择了一行,则:

SELECT t3.rc, t2.rcs
FROM   t2
       INNER JOIN t3
       ON t3.rc LIKE t2.rcs || '%'
ORDER BY LENGTH(t2.rcs) DESC
FETCH FIRST ROW ONLY

如果t3中有多行,并且希望每行都有最佳匹配,则:

SELECT t3.rc,
       t2.rcs
FROM   t3
       CROSS JOIN LATERAL (
         SELECT rcs
         FROM   t2
         WHERE  t3.rc LIKE t2.rcs || '%'
         ORDER BY LENGTH(t2.rcs) DESC
         FETCH FIRST ROW ONLY
       ) t2

或:

SELECT rc,
       rcs
FROM   (
  SELECT t3.rc,
         t2.rcs,
         ROW_NUMBER() OVER (PARTITION BY t3.rc ORDER BY LENGTH(t2.rcs) DESC) AS rn
  FROM   t2
         INNER JOIN t3
         ON t3.rc LIKE t2.rcs || '%'
)
WHERE  rn = 1;

对于您的示例数据,所有输出:
| RC|雷达散射截面|
| - ------|- ------|
| 小行星441|四四一|
fiddle

相关问题