Моя попытка:
/* -- sample data
with titles(book) as (
select 'Hamlet' from dual union all
select 'Othello' from dual union all
select 'Macbeth' from dual union all
select 'King Lear' from dual ),
books (usr, book) as (
select 'Alan', 'Hamlet' from dual union all
select 'Alan', 'Othello' from dual union all
select 'Alan', 'Macbeth' from dual union all
select 'Alan', 'King Lear' from dual union all
select 'Alan', 'Hamlet' from dual union all
select 'Alex', 'Hamlet' from dual union all
select 'Anna', 'King Lear' from dual union all
select 'Ella', 'Macbeth' from dual union all
select 'Ella', 'King Lear' from dual union all
select 'Emma', 'Macbeth' from dual union all
select 'Jack', 'Othello' from dual union all
select 'Jade', 'Hamlet' from dual union all
select 'John', 'Macbeth' from dual union all
select 'Noah', 'Othello' from dual union all
select 'Nora', 'Hamlet' from dual union all
select 'Seth', 'Hamlet' from dual union all
select 'Seth', 'Othello' from dual union all
select 'Seth', 'Macbeth' from dual union all
select 'Seth', 'King Lear' from dual ),
*/ -- end of sample data
with
tmp as (
select grp, sys_connect_by_path(book, '#') path, level cnt
from (select row_number() over (order by book) grp, book from titles)
connect by book > prior book),
groups as (
select grp, path, cnt, trim(column_value) book
from tmp, xmltable(('"'||replace(ltrim(path,'#'), '#', '","')||'"')))
select path, count(1) cnt, listagg(usr, ', ') within group (order by usr) users
from (
select usr, path, grp
from groups g join (select distinct usr, book from books) b on b.book = g.book
group by usr, path, cnt, grp
having cnt = count(1))
group by path
Кажется, вам нужны все комбинации групп книг.Я использовал иерархический запрос, а затем разбил результат функции sys_connect_by_path()
на строки, чтобы добиться этого.
Следующий шаг - объединить эти группы с таблицей books
, подсчитать количество книг для каждого пользователя и, если это число меньше, чем количество книг в группе - удалить его из результата.
В конце я только группирую пользователей, чтобы посчитать их и представить в виде списка.Результат:
PATH CNT USERS
---------------------------------- ---------- -------------------------------
#Hamlet 5 Alan, Alex, Jade, Nora, Seth
#Hamlet#King Lear 2 Alan, Seth
#Hamlet#King Lear#Macbeth 2 Alan, Seth
#Hamlet#King Lear#Macbeth#Othello 2 Alan, Seth
#Hamlet#King Lear#Othello 2 Alan, Seth
#Hamlet#Macbeth 2 Alan, Seth
#Hamlet#Macbeth#Othello 2 Alan, Seth
#Hamlet#Othello 2 Alan, Seth
#King Lear 4 Alan, Anna, Ella, Seth
#King Lear#Macbeth 3 Alan, Ella, Seth
#King Lear#Macbeth#Othello 2 Alan, Seth
#King Lear#Othello 2 Alan, Seth
#Macbeth 5 Alan, Ella, Emma, John, Seth
#Macbeth#Othello 2 Alan, Seth
#Othello 4 Alan, Jack, Noah, Seth