题解|19. 鬼畜区的用户里有多少用户看过汽车区
鬼畜区的用户里有多少用户看过汽车区
明确题意:
计算鬼畜区的用户里,有多少用户看过汽车区。 对于本题,等价于计算既看过鬼畜区又看过汽车区的用户数。
问题拆解:
有两种解法。解法1:用鬼畜区用户join汽车区用户。
- 关联视频类型,只保留鬼畜和汽车类的视频,并取唯一结果。知识点:关联表join;筛选类型where in;取唯一distinct;
- 筛选出鬼畜区的用户。知识点:where
- 筛选出汽车区的用户。知识点:where
- 关联两批用户。知识点:join
- 对用户计数。知识点:count
解法2:只保留每个用户观看的鬼畜区或汽车区的用户ID、区域类型;筛选观看过的这两个类型的类型个数为2的用户数。
- 关联视频的类型。知识点:join
- 筛选视频类型为鬼畜或汽车的记录。知识点:where
- 统计观看过这些区的区域个数为2的用户。知识点:按用户分组gourp by;对观看区域个数计数count(distinct vidio_type)=2
- 对满足上述条件的用户计数。知识点:count
代码实现:
with t_user_vidio_type as (
select distinct user_id, vidio_type
from user_view_tb
join vidio_info_tb using (vidio_id)
where vidio_type in ("鬼畜", "汽车")
)
select count(user_id)
from (
select user_id from t_user_vidio_type
where vidio_type="鬼畜"
) as t_evil
join (
select user_id from t_user_vidio_type
where vidio_type="汽车"
) as t_car
using(user_id)
select count(distinct user_id) as num
from (
select user_id
from user_view_tb
join vidio_info_tb using (vidio_id)
where vidio_type in ("鬼畜", "汽车")
group by user_id
having count(distinct vidio_type)=2
)