0

I have to select the most common values in the columns of a table, and output it in a table, but I don't know how to do it (in a single query)

here is my table 'stats':

Page | Referrer | Useragent
__________________________
bla  | bla bla  | bla bla

My code:

echo "<table><tr><td>page</td><td>referrer</td><td>useragent</td></tr>";
$stmt = $db-prepare("SELECT `page`, COUNT(`page`) AS FREQ FROM  `stats` GROUP BY `page` ORDER BY FREQ DESC LIMIT 1");
$stmt->execute();
$result = $stmt->fetch();
echo "<tr><td>{$result['page']}</td>";
// and so on with the other two columns

Is there a best way to do it?

And if the query returns two values? (there are two values in the column that appears exactly the same time, and both are the most frequent)

wogsland
  • 9,106
  • 19
  • 57
  • 93
  • The accepted answer in the linked question shows how to get one row, but there's a later answer that shows how to get all the rows with the most frequent value. – Barmar Dec 28 '15 at 15:48
  • http://stackoverflow.com/questions/9853671/sql-select-most-common-values – xQbert Dec 28 '15 at 15:49
  • @Barmar I'm not sure this answers the question as I don't see how the linked answer handles ties. – xQbert Dec 28 '15 at 15:51
  • [the third answer](http://stackoverflow.com/a/18029066/1491895) handles ties. – Barmar Dec 28 '15 at 15:54

0 Answers0