mysql 计数,然后按该计数分组

mysql count and then group by that count

我有一个 table 结构如下:

user_id   saved_id
1         2
1         34
1         36
2         489
2         14
3         731
4         48
5         901
6         234
6         9
6         64

我想做的是首先计算每个用户保存了多少个 id,然后对这些结果进行分组,以便我知道每个 total_saves 出现的频率。

这是我目前拥有的:

SELECT user_id, count(*) as total_saves FROM table GROUP BY user_id ORDER BY total_saves DESC

这给了我

user_id   total_saves
1         3
6         3
2         2
3         1
4         1
5         1

我想要的是:

total_saves   count
3             2
2             1
1             3

无法理解如何对已有的 total_saves 进行分组。我尝试了 GROUP BY total_saves 但那不起作用。

使用两个聚合:

select total_saves, count(*) as cnt
from (select user_id, count(*) as total_saves
      from t
      group by user_id
     ) t
group by total_saves;

使用子查询

select total_saves, count(total_saves) as count
from (select user_id, count(*) as total_saves
  from table
  group by user_id
 ) a
group by total_saves order by total_saves;