Вопрос

I am trying to find the largest number of distinct values in a database. The code I have so far is:

$highestStats = 0;
$highest = $bdd->query('SELECT count(DISTINCT month) FROM stats')->fetchColumn();
while($highestData = $highest) {
    if ($highestStats < $highestData['month']) {
        $highestStats = $highestData['month'];
    }
}
echo $highestStats;

This code doesn't work.

My example is this: there is a list of months in the database and for example February is listed 4 times, march 9 times and April 7 times. Basically I want $highestStats to retun 9. i.e. the number of times the most used month appears.

How should I go about doing this, $bdd is a PDO MySQL connection.

Any help is much appreciated.

Cheers Jim

Это было полезно?

Решение

Think you can use a sub query to do this:-

SELECT MAX(month_occurs)
FROM
(
    SELECT `month`, COUNT(*) AS month_occurs
    FROM stats 
    GROUP BY `month`
) Sub1

Or avoiding a sub query but using an order by / limit

SELECT `month`, COUNT(*) AS month_occurs
FROM stats 
GROUP BY `month`
ORDER BY month_occurs DESC
LIMIT 1

Другие советы

try this:

select c,month from (SELECT count(month) as c,month from states group by month)temp order by c desc limit 1;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top