简体   繁体   English

这里如何申请group by?

[英]How to apply group by here?

I have a table Movie with columns Movie and Viewer where each movie is viewed by any user any number of times, so the table can have multiple same entries.我有一个包含MovieViewer列的 Movie 表,其中任何用户都可以多次观看每部电影,因此该表可以有多个相同的条目。 I want to find the Top N most viewed movies and then the Top K viewers for each of the Top N movies.我想找到前 N 部观看次数最多的电影,然后是每部前 N 部电影的前 K 名观众。 How can I apply group by or partition by effectively in such scenario?在这种情况下如何有效地应用分组依据或分区依据? Or if there is any better approach to this, please share.或者如果有更好的方法,请分享。 Thanks!谢谢!

Movie电影 User用户
Avengers复仇者联盟 John约翰
Batman蝙蝠侠 Chris克里斯
Batman蝙蝠侠 Ron罗恩
X-Men X战警 Chris克里斯
X-Men X战警 Ron罗恩
Matrix矩阵 John约翰
Batman蝙蝠侠 Martin马丁
Matrix矩阵 Chris克里斯
Batman蝙蝠侠 Chris克里斯
X-Men X战警 Ron罗恩

So, in this table Batman is the most watched movie is Batman followed by X-Men so I want the result table to look like:所以,在这张表中,蝙蝠侠是观看次数最多的电影是蝙蝠侠,其次是 X 战警,所以我希望结果表看起来像:

Movie电影 User用户 View count查看次数
Batman蝙蝠侠 Chris克里斯 2 2个
Batman蝙蝠侠 Ron罗恩 1 1个
Batman蝙蝠侠 Martin马丁 1 1个
X-Men X战警 Ron罗恩 2 2个
X-Men X战警 Chris克里斯 1 1个
Matrix矩阵 John约翰 1 1个
Matrix矩阵 Chris克里斯 1 1个
Avengers复仇者联盟 John约翰 1 1个

I understand that I can group by movie and then do order by count(*) desc but this doesn't give me the second column which is grouped by viewer and the count for each viewer also.我知道我可以按电影分组,然后按 count(*) desc 进行排序,但这并没有给我第二列,它是按观众分组的,也没有给我每个观众的计数。

Consider below approach (assuming Top 3 movies with Top 2 users)考虑以下方法(假设 Top 3 电影有 Top 2 用户)

select movie, user, view_count
from (
  select distinct *,  
    count(*) over(partition by movie) movie_views,
    count(*) over(partition by movie, user) view_count
  from your_table
)
qualify dense_rank() over(order by movie_views desc) <=3 
and row_number() over(partition by movie order by view_count desc) <=2
-- order by movie_views desc, view_count desc     

if applied to sample data in your question - output is如果应用于您问题中的示例数据 - output 是

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM