关于分组2列的SQL select查询

时间:2012-06-28 13:41:19

标签: mysql sql select group-by

我试图了解这个问题 - 看起来非常简单

下表列出了哪个用户观看了哪个视频

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.

需要一些帮助。

提前致谢

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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)

答案 3 :(得分: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

答案 4 :(得分: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)有多少用户观看了不同的视频节目。

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