0

有帮助显示结果的帮助,它没有显示我需要的结果。

我有这个

表名 = power 列名 = power1, power2, power2, power4, power5

 $res = mysql_query("select power1, power2, power2, power4, power5, 
 count(*) as cnt 
 from power 
 group by power1, power2, power2, power4, power5 
 order by cnt desc limit 5;");

它显示了表格中的特定行,而不仅仅是表格中最常见的 5 个数字

the table entries

the results

如您所见,它显示的是第二行,而不是显示前 5 个数字(至少应该显示数字 1,5 和 2)。

任何想法都会受到极大的欢迎。

非常感谢

保罗

4

3 回答 3

5

col要获取表中列中最常见的 5 个值x

select col, count(*) as cnt
from x
group by col
order by cnt desc
limit 5;

如果您试图在五列中获取五个最常见的数字(在我的原始答案之后对问题进行了重大更改),这是一种方法:

select power, count(*) as cnt
from (select (case when n = 1 then power1
                   when n = 2 then power2
                   when n = 3 then power3
                   when n = 4 then power4
                   when n = 5 then power5
              end) as power
      from power p cross join
           (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5
           ) n
     ) p

这会将所有列放在一个列中,然后返回最常见的值。

于 2013-05-20T14:54:43.417 回答
0

要获得所有列中最常见的前 5 个值,您必须加入表 5 次

 Select top 5 val From
 (Select power1 val From table
  Union Select power2 val From table
  Union Select power3 val From table
  Union Select power4 val From table
  Union Select power5 val From table) z
 Group By val
 Order By Count(*) Desc
于 2013-05-20T18:29:57.627 回答
0
Select Z.Num, Count(*) As Cnt
From    (
        Select power1 As Num From power
        Union All Select power2 From power
        Union All Select power3 From power
        Union All Select power4 From power
        Union All Select power5 From power
        ) As Z
Group By Z.Num
Order By Count(*) Desc
Limit 5

确保您使用Union All,否则您将获得1每个离散数字的计数。

SQL 小提琴版本

于 2013-05-22T01:08:12.507 回答