If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Most frequent value

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 10-08-06, 15:32
Spiff2 Spiff2 is offline
Registered User
 
Join Date: Oct 2006
Posts: 2
Most frequent value

I have a table with a int field of which I want the most frequent value. If rows contain the values, 8, 4, 8, 2, 9, the query I'm searching for would return 8. My current solution is to go through all records, and count the frequency of the values using PHP. I hope there is a better solution, something like:

select * from table1 order by frequency(row1) desc
Reply With Quote
  #2 (permalink)  
Old 10-08-06, 16:17
dbmab dbmab is offline
Registered User
 
Join Date: Apr 2006
Location: Denver, Co. USA
Posts: 240
This will probably work -
select your_column_name, count(*) as cnt from table1 group by your_column_name order by cnt desc limit 1

This will return one row with the value followed by the count of that value. If there are ties, it will return the one which it encountered first (lowest row number). To let your PHP program deal with ties, increase the limit x number or eliminate the limit x clause if you want all the results.
Reply With Quote
  #3 (permalink)  
Old 10-08-06, 16:36
Spiff2 Spiff2 is offline
Registered User
 
Join Date: Oct 2006
Posts: 2
Indeed it works, and cts contains the number of times the most frequent values occurs! Great, thanks.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On