我有一个像这样的结构表:
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
,但这不起作用。
答案 0 :(得分:4)
使用两个聚合:
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;
答案 1 :(得分:0)
使用子查询
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;