2016-07-22 20 views
3

Ich habe eine Tabelle wie folgt strukturiert:mysql Zahl und dann die Gruppe durch das zählt

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 

Was ich zuerst tun möchte wird zählen, wie viele gespeicherte IDs jeder Benutzer hat, und dann die Gruppe diese Ergebnisse, so dass Ich weiß, wie oft jedes total_saves auftritt.

Dies ist, was ich derzeit haben:

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

Was mich gibt

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

Was ich möchte, ist dies haben:

total_saves count 
3    2 
2    1 
1    3 

meinen Kopf kann nicht bekommen um, wie die total_saves gruppiert werden, die ich bereits habe. Ich versuchte GROUP BY total_saves, aber das funktioniert nicht.

Antwort

4

Verwenden zwei Aggregationen:

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

Verwenden 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;