[英]mysql count and then group by that count
我有一個像這樣結構的表:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.