tags:

views:

116

answers:

4

I have a colum in mysql table that is INT(11).

How can i search to get the 10 most occurring values in this column?

+2  A: 

Try:

SELECT ColName, Count(1) AS occurances
    FROM
        table
    GROUP BY
        ColName
    ORDER BY
        occurances DESC
    LIMIT
        10
jammus
+5  A: 
SELECT col, count(*)
    FROM tablethingie
    GROUP BY col
    ORDER BY count(*) DESC
    LIMIT 10
Michael Krelin - hacker
Flagged my answer for delete (-: Is it possible to use count(col) rather than count(*) ? Hmm, and which is more efficient...
Murph
Ok, I guess you were the first to alter the mysql :-), I delete my thus and vote this one.
Peter
count(col) will count non-null values. Since col is what we group on, it's the same, anyway. count(*) is equivalent to count(1), but is generally recommended over the latter. count(*) is supposed to be the most efficient of all as long as it's exactly what you need.
Michael Krelin - hacker
Peter, mysql races! ;-) But what do you mean "alter"? The only thing I've altered when editing the answer was formatting, IIRC.
Michael Krelin - hacker
+2  A: 

TOP is a keyword which is not supported in MySQL, it is in MSSQL though.

This following query should do what you want (untested, but the idea should become clear):

SELECT column, COUNT(*) AS matches FROM table GROUP BY column ORDER BY matches DESC LIMIT 10

Ben Fransen
Up-voted to counter the down-vote; since, so far as I can tell, your answer is equally valid to all the others. I do wish that down-voters would *explain* their down-votes, though. That way we can learn something.
David Thomas
ricebowl, would that explain it? - http://stackoverflow.com/revisions/1831456/list - the answer was edited to mimic others after being downvoted ;-)
Michael Krelin - hacker
Indeed, because i saw an error in my answer, so i corrected it. This way there are provided correct answers and not non-working. Keeping high the quality of answers to a question.
Ben Fransen
Ben Fransen, I do not think you've done something severely wrong. It is more common to delete your answer and upvote the correct one, but your behaviour is by no means criminal ;-) It's just that it explains the downvote. (which was mine and I revoked it).
Michael Krelin - hacker
No hard feelings, cheers! :)
Ben Fransen
@hacker, that does explain, but a comment explaining the down-vote would've been faster. ...yeah; I'm maybe being lazy in my old age =)
David Thomas
+3  A: 
  SELECT colname, COUNT(*) AS cnt
    FROM tablename
GROUP BY colname
ORDER BY cnt DESC
   LIMIT 10
Josh Davis