Sunday, January 11, 2009

MySQL: Grouping by most occurence in Column

I was developing a Content Management System (CMS) software when I encountered this issue of displaying most occurrence. So I managed to do this:

mysql> SELECT `DesireColumn`, COUNT(`DesireColumn`) AS `occurances` FROM `table` GROUP BY `DesireColumn` ORDER BY `occurances` DESC

This query groups rows with same value in `DesireColumn`, then sorts the result by the number of occurances. It's useful to me, and I hope that it's useful to you too.


Darkstar Media said...

Thank you, i found this very useful...

thephpdeveloper said...

hey there!
no problem at all =D