MySQL频率报告的频率

时间:2017-03-14 12:38:54

标签: mysql

鉴于许多用户有很多帖子

我有一个包含外键user_id的帖子表

我想生成一个报告,显示用户对帖子频率的频率

e.g。

3个用户分别写了2个帖子

2位用户每篇写了1篇

1位用户写了4篇帖子

Number of users | Number of posts
--------------- | ------------------
1               | 4
2               | 1
3               | 2  

我的尝试:

SELECT inner_table.frequency_posts, 
       Count(*) AS frequency_users
FROM   posts 
       INNER JOIN (SELECT user_id, 
                          Count(*) AS frequency_posts 
                   FROM   posts
                   GROUP  BY user_id) AS inner_table 
               ON posts.user_id = inner_table.user_id
GROUP  BY inner_table.frequency_posts

我认为frequency_posts正在运作,但是计算frequency_users并没有给出正确的值 - 当我查看它自己的内部选择并手动添加帖子时我不会得到相同的值值

1 个答案:

答案 0 :(得分:1)

您必须使用Group by两次:

SELECT     
  COUNT(*) AS NumberOfUsers,
  foo.NumberOfPosts
FROM
    (SELECT 
        p.UserId AS UserId, 
        COUNT(*) AS NumberOfPosts
    FROM
        posts AS p
    GROUP BY UserId) as foo
GROUP BY foo.NumberOfPosts