2

次のデータを含むテーブルがあります。

User#       App
1       A
1       B
2       A   
2       B
3       A

個別のユーザーによるアプリ間の重複を知りたいので、私の最終結果は次のようになります

App1  App2  DistinctUseroverlapped 
A     A     3
A     B     2
B     B     2

つまり、アプリ A のみを使用しているユーザーが 3 人、アプリ A とアプリ B の両方を使用しているユーザーが 2 人、アプリ B のみを使用しているユーザーが 2 人いることを意味します。

多くのアプリとユーザーが SQL でこれを行うにはどうすればよいか覚えていますか?

4

2 に答える 2

2

私のソリューションは、関心のあるすべての可能なアプリケーションのペアを生成することから始まります。これがdriverサブクエリです。

次に、各アプリの元のデータに結合します。

最後にcount(distinct)、2 つのリスト間で一致する個別のユーザーをカウントするために使用します。

select pairs.app1, pairs.app2,
       COUNT(distinct case when tleft.user = tright.user then tleft.user end) as NumCommonUsers
from (select t1.app as app1, t2.app as app2
      from (select distinct app
            from t
           ) t1 cross join
           (select distinct app
            from t
           ) t2
      where t1.app <= t2.app
     ) pairs left outer join
     t tleft
     on tleft.app = pairs.app1 left outer join
     t tright
     on tright.app = pairs.app2
group by pairs.app1, pairs.app2

の条件付き比較をcount結合に移動して、次を使用できますcount(distinct)

select pairs.app1, pairs.app2,
       COUNT(distinct tleft.user) as NumCommonUsers
from (select t1.app as app1, t2.app as app2
      from (select distinct app
            from t
           ) t1 cross join
           (select distinct app
            from t
           ) t2
      where t1.app <= t2.app
     ) pairs left outer join
     t tleft
     on tleft.app = pairs.app1 left outer join
     t tright
     on tright.app = pairs.app2 and
        tright.user = tleft.user
group by pairs.app1, pairs.app2

私は最初の方法を好みます。これは、何をカウントするかがより明確になるためです。

これは標準 SQL であるため、Vertica で動作するはずです。

于 2013-04-18T21:41:31.327 に答える
0

これはvertica 6で動作します

 with tab as 
    ( select 1 as user,'A' as App
    union  select 1 as user,'B' as App
    union select 2 as user,'A' as App
    union select 2 as user,'B' as App
    union select 3 as user,'A' as App
    )
    , apps as 
    ( select distinct App  from tab )
    select apps.app as APP1,tab.app as APP2 ,count(distinct tab.user) from tab,apps
    where tab.app>=apps.app
    group by 1,2
    order by 1
于 2013-08-14T19:53:33.413 に答える