使用Max和Count查询时返回字段名称

时间:2013-10-12 22:32:41

标签: mysql sql

似乎无法想出这个......

我有一个表,其中一个字段是variabletype。有几种用户输入变量类型。例如:

id | variabletype
 1 | button
 2 | text
 3 | button
 4 | link
 5 | button
 6 | link

我写了一些SQL来基本计算列出每个变量类型的次数。我将其嵌入到子查询中,以便我可以获得具有最大实例数的记录(在此示例中为 - 按钮)。

我的问题是查询只返回最大数字,它不显示实际的变量类型。我理想的结果是变量类型显示以及最大计数。有什么想法吗?

 SELECT MAX(y.mosttested)
   FROM (SELECT variabletype, COUNT(variableid) AS mosttested
     FROM variable GROUP BY variabletype) y

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT `variabletype `,
       COUNT(`variabletype `) AS `value_occurrence` 
FROM   `my_table`
GROUP BY `value`
ORDER BY `value_occurrence` DESC
LIMIT    1;

答案 1 :(得分:0)

尝试

select variabletype,n
from 
  (SELECT variabletype, COUNT(variableid) AS mosttested
  FROM variable GROUP BY variabletype) v 
where mosttested=(SELECT MAX(y.mosttested) AS n
   FROM (SELECT variabletype, COUNT(variableid) AS mosttested
     FROM variable GROUP BY variabletype) y)

答案 2 :(得分:0)

如果您的SQL环境中有row_number函数,那么您可以执行以下操作:

SELECT y.variabletype, y.mosttested as max_mosttested
   FROM (SELECT variabletype, COUNT(variableid) AS mosttested, row_number()over(order by count(variableid) desc)
     FROM variable GROUP BY variabletype) y
where rownum=1