PHP SQL查找前5个最重复的值

时间:2017-04-23 03:47:52

标签: php sql mysqli

我有一个数据库,我通过PHP和mysqli访问。我需要获得前5个最重复的值。

例如,   数据库将包含在其中 1,1,2,2,2,4,6,5,5,5,5,

数据库应该连续打印

:5,2,1,4,6

3 个答案:

答案 0 :(得分:2)

您是否在询问SQL查询将最少发生的事情是什么?

这里将按数字分组,然后从大多数出现到最少出现

SELECT number , count(number) as 'occurrences' 
FROM my_table 
GROUP BY number 
ORDER BY count(number) DESC

答案 1 :(得分:0)

Try this code snippet here

<?php
ini_set('display_errors', 1);
$array=array(1, 1, 2, 2, 2, 4, 6, 5, 5, 5, 5);
$data=array_count_values($array);//counting the no. of values in an array
arsort($data);//sorting array in descending order
print_r(array_keys($data));//getting the key of array which is the desired output

答案 2 :(得分:0)

如果您需要将结果作为字符串(连续):

SELECT STUFF((SELECT ',' + convert(varchar,my_number) FROM my_table group by 
my_number ORDER BY count(my_number) desc for XML PATH('')), 1, 1, '')