我正在努力解决这个问题 - 看起来很简单
下表记录了哪个用户观看了哪个视频
topic_user_id | topic_id | user_id 1 | 10 | 3 2 | 10 | 4 3 | 11 | 5 4 | 11 | 3 5 | 12 | 6 6 | 13 | 6 7 | 14 | 7 8 | 11 | 8 9 | 11 | 9 10 | 14 | 10 11 | 15 | 11 12 | 16 | 11 13 | 17 | 11
现在要了解有多少用户观看了特定视频 - 我有以下查询。
有多少用户观看了特定视频
select count(distinct(user_id)) as 'Number of Users',topic_id from topic_user where user_id is not null group by topic_id
输出
Number of Users | topic_id 2 | 10 4 | 11 1 | 12 1 | 13 2 | 14 1 | 15 1 | 16 1 | 17 Read as: 2 users watched topic 10 , 4 watched topic 11 and so on
这工作正常 - 但我正在寻找的是找到:
有多少用户观看了 1 个视频
有多少用户观看了 2 个视频
有多少用户观看了 3 个视频
输出应该是这样的
Number of Users | Number of Videos watched 6 | 1 2 | 2 1 | 3 Read as - 6 people watched only 1 video, 2 people watched 2 videos and so on.
需要一些帮助。
提前致谢
最佳答案
可能有更简单的方法,但子查询会起作用
select
videos as 'Number of videos',
count(user_id) as 'Num of Users'
from (
select
count(distinct(topic_id)) as videos,
user_id from topic_user
group by
user_id
) sub
group by
videos
关于mysql - 关于分组 2 列的 SQL 选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11245989/