Как сравнить две колонки с предложениями разбивая их по пробелу и сравнивая каждое слово?
Есть таблица и в ней две колонки:
col1 col2
--------------------- -------------------------
best buy card credit credit no take buy order
Длина колонок не фиксирована, т.е. количество слов может быть любое.
Нужно сравнить слова в обоих столбцах и вернуть количество совпадающих слов.
Ожидаемый результат - 2 слова buy, credit.
Каким запросом можно добится этого?
Свободный перевод вопроса Match the words in two columns oracle sql by breaking the string and comparing each word от участника @user2342436
Ответы (1 шт):
Автор решения: 0xdb
→ Ссылка
Преобразовать обе колонки в табличные значения, затем полученые таблицы соединить.
Воспроизводимый пример:
create table t (id int, col1 varchar2 (96), col2 varchar2 (96))
/
insert all
into t values (1, 'best buy card credit', 'credit no take buy order')
into t values (2, 'aaa bbb ccc', 'ccc ddd fff')
into t values (3, 'aaa bbb ccc', 'zzz yyy xxx') select * from dual;
with t1 (id, col, val) as (
select id, col1, trim (column_value)
from t, xmlTable (('"'||replace (t.col1, ' ', '","')||'"')) x
),
t2 (id, col, val) as (
select id, col2, trim (column_value)
from t, xmlTable (('"'||replace (t.col2, ' ', '","')||'"')) x
)
select t1.id,
listagg (t2.val, ',') within group (order by t2.val) "words",
count (t2.id) "total matched"
from t1
left join t2 on (t2.id = t1.id and t2.val = t1.val)
group by t1.id
/
Результат:
ID words total matched
---------- ---------------- -------------
1 buy,credit 2
2 ccc 1
3 0