我有一个包含以下数据的表格:
User# App
1 A
1 B
2 A
2 B
3 A
我想知道不同用户的应用程序之间的重叠,所以我的最终结果如下所示
App1 App2 DistinctUseroverlapped
A A 3
A B 2
B B 2
所以结果意味着有 3 个用户仅使用应用程序 A,有 2 个用户同时使用应用程序 A 和应用程序 B,还有 2 个用户仅使用应用程序 B。
还记得有很多应用程序和用户,我如何在 SQL 中执行此操作?
最佳答案
我的解决方案首先生成所有可能感兴趣的应用程序对。这是driver
子查询。
然后它会加入每个应用程序的原始数据。
最后,它使用 count(distinct)
来计算两个列表之间匹配的不同用户。
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 上运行。
关于sql - SQL 中的重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16093468/