2016-11-01 6 views
0

私はビデオ再生サイトのデータベースを作成しています。ユーザーと表が表示された表があります。私はいくつかの見ているビデオのペアをSQLクエリを使用して見つける必要があります。例:ユーザー1がビデオ12,43,50,66,78を視聴した。ユーザー2は12,43,45,50を視聴しました。ユーザー3は12,35,50,66,78を監視しました。ユーザー4が視聴した回数33,66,69,78 2人の視聴カップルは(12,50)と(66,78)です。 しかし、私はこのカップルを将来の世代のために形成する方法さえも得られません。 私の質問は、すべての可能なカップルを形成し、それぞれのビューの数を数える方法です。最も頻繁に使用されるペアを作成してカウントするoracle

+1

'group by user、movie' – jarlh

+0

@jarlh - care to elaborate?私は、ユーザーが映画をどのようにグループ化しているのか分からない。 – mathguy

答えて

0

自己joinはこれを行うには正しい方法です。私は最も簡単なクエリの形式は、

select vh.* 
from (select vh1.movie as movie1, vh2.movie as movie2, count(*) as cnt, 
      rank() over (order by count(*) desc) as seqnum 
     from viewing_history vh1 inner join 
      viewing_history vh2 
      on vh1.userid = vh2.userid and vh1.movie < vh2.movie 
     group by vh1.movie, vh2.movie 
    ) vh 
where seqnum = 1; 
0

下のソリューションでは、入力データをシミュレートするためのサブクエリを作成します。アプリケーションでは、viewing_historyの代わりに、視聴履歴テーブルを使用する必要があります。この問題で "users"テーブルがどのように関係しているかわかりません。 movie_pairsという名前の2番目のサブクエリは、ビュー履歴の内部結合であり、ペアを作成する方法です。私はそれを超えました - それと同時に、私は最も頻繁に一緒に見られるペアを特定するために続けました。

with 
    viewing_history (userid, movie) as (
     select 1, 12 from dual union all 
     select 1, 43 from dual union all 
     select 1, 50 from dual union all 
     select 1, 66 from dual union all 
     select 1, 78 from dual union all 
     select 2, 12 from dual union all 
     select 2, 43 from dual union all 
     select 2, 45 from dual union all 
     select 2, 50 from dual union all 
     select 3, 12 from dual union all 
     select 3, 35 from dual union all 
     select 3, 50 from dual union all 
     select 3, 66 from dual union all 
     select 3, 78 from dual union all 
     select 4, 33 from dual union all 
     select 4, 66 from dual union all 
     select 4, 69 from dual union all 
     select 4, 78 from dual 
    ), 
-- end test data, query begins here (but include the keyword WITH from above) 
    movie_pairs (movie1, movie2, ct) as (
     select  a.movie, b.movie, count(*) 
     from  viewing_history a inner join viewing_history b 
         on a.userid = b.userid and a.movie < b.movie 
     group by a.movie, b.movie 
    ) 
select movie1, movie2 
from movie_pairs 
where ct = (select max(ct) from movie_pairs) 
order by movie1, movie2 -- ORDER BY is optional 
; 

出力

MOVIE1  MOVIE2 
---------- ---------- 
     12   50 
     66   78  
関連する問題