4

我正在努力解决这个问题 - 看起来很简单

下表捕获了哪个用户观看了哪个视频

topic_user_id | 主题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

现在要找出有多少用户观看了特定视频 - 我有以下查询。

有多少用户观看了特定视频

从 topic_user 中选择 count(distinct(user_id)) 作为“用户数”,topic_id
其中 user_id 不为空
按 topic_id 分组

输出

用户数量 | topic_id
    2 | 10     
    4 | 11     
    1 | 12     
    1 | 13     
    2 | 14     
    1 | 15     
    1 | 16     
    1 | 17     

读作:2 位用户观看了主题 10 ,4 位用户观看了主题 11 等等

这工作正常 - 但我正在寻找的是找到:

有多少用户观看了 1 个视频
有多少用户观看了 2 个视频
有多少用户观看了 3 个视频

输出应该类似于

用户数量 | 观看的视频数
      6 | 1
      2 | 2
      1 | 3

阅读为 - 6 人仅观看了 1 个视频,2 人观看了 2 个视频,依此类推。

需要一些帮助。

提前致谢

4

5 回答 5

2

可能有更简单的方法,但子查询会起作用

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
于 2012-06-28T13:48:45.327 回答
1
select u.n as `Number of Video watched`, count(t.user_id)
from
    (select user_id, count(*) as `cnt`
    from topic_user 
    group by user_id) t INNER JOIN(
        SELECT 1 as `n` FROM DUAL 
        UNION 
        SELECT 2 as `n` FROM DUAL 
        UNION
        SELECT 3 as `n` FROM DUAL) u ON u.n = t.cnt
group by u.n

小提琴:http ://sqlfiddle.com/#!2/844ee/15

于 2012-06-28T14:12:00.777 回答
0

尝试这个

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_query
GROUP BY
videos
于 2012-06-28T14:05:49.750 回答
0

尝试这个::

Select first_table.count(distinct(user_id))  as 'Number of Users', SUM(Count(topic_id))
from
(select count(distinct(user_id)) as 'Number of Users',topic_id from topic_user
where user_id is not null
group by topic_id) as first_table group by Count(topic_id)
于 2012-06-28T13:48:26.587 回答
0

“有多少用户观看了 n 个视频”可以解释为两种方式:

1) 无论标题如何,有多少用户观看了 n 个视频?同一视频标题可能已被观看两次。

select videoCount, count(*) as userCount
  from (
    select count(*) as videoCount
      from topic_user
    group by user_id
  ) t
 group by videoCount

2) 有多少用户观看了 n 个不同的视频标题。

select videoCount, count(*) as userCount
  from (
    select count(distinct topic_id) as videoCount
      from topic_user
    group by user_id
  ) t
 group by videoCount
于 2012-06-28T14:14:23.630 回答