2016-07-22 42 views
3

我有一個表的結構是這樣的:MySQL的計數,然後由該組數

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 

我想要做的是先算多少保存IDS每個用戶都有,然後組這些結果使我知道每個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但這不起作用。

回答

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; 
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; 
相關問題