简体   繁体   English

mysql计数然后按该计数分组

[英]mysql count and then group by that count

I have a table structured like this: 我有一个像这样结构的表:

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

What I would like to do is first count how many saved ids each user has, and then group these results so that I know how often each total_saves occurs. 我想要做的是首先计算每个用户有多少已保存的ID,然后将这些结果分组,以便我知道每个total_saves发生的频率。

This is what I currently have: 这就是我目前拥有的:

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

Which gives me 哪能给我

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

What I would like to have is this: 我想拥有的是:

total_saves   count
3             2
2             1
1             3

Can't get my head around how to group the total_saves that I already have. 无法理解如何对我已经拥有的total_saves进行分组。 I tried GROUP BY total_saves but that doesn't work. 我尝试了GROUP BY total_saves但这不起作用。

Use two aggregations: 使用两个聚合:

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;

Use Subquery 使用子查询

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM