Get the highest Matched output in result
It's something like this ... Since I dont have your exact table in my database it could be slightly wrong. But this is 80% or 99% what you're asking.

$query = db_select('my_table', 't')
    -&gt;fields('t', array('UserID'))
    -&gt;condition('contentID', 31)
    -&gt;groupBy('UserID')
    -&gt;orderBy(2, 'DESC');
$query-&gt;addExpression('COUNT(t.UserID) AS num_items');
$results = $query-&gt;execute();

// dpm() is in the Devel module.
foreach ($results as $record) { dpm($record); }


EDIT:

The final query that worked was:

$query = db_select('flag_content','fcnt')
-&gt;fields('fcnt', array('uid'))
-&gt;condition('fcnt.content_id', array(178,225), 'IN')
-&gt;groupBy('fcnt.uid')
-&gt;orderBy('num_items', 'DESC');
$query-&gt;addExpression('COUNT(*)' , 'num_items');