简体   繁体   English

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

[英]PHP SQL Find Top 5 Most Repeated Values

I have a database that I am accessing through PHP and mysqli. 我有一个通过PHP和mysqli访问的数据库。 I need to get the top 5 most repeated values. 我需要获取前5个最重复的值。

For example, the database would have in it 1, 1, 2, 2, 2, 4, 6, 5, 5, 5, 5, 例如,数据库中将包含1,1,2,2,2,4,4,6,5,5,5,5,

The database should print out in a row 数据库应连续打印

: 5, 2, 1, 4, 6 :5,2,1,4,6

Are you asking what the SQL query would be to get most occurances to least? 您是在问什么将使发生次数最少的SQL查询吗?

this here will group by the number and then order it from most occurances to the least 这将按数字分组,然后按出现次数从大到小排列

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

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

If you need the result as a string (in a row): 如果需要将结果作为字符串(连续):

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, '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM