返回select语句SQL的最大值

时间:2012-10-09 13:30:01

标签: mysql sql oracle

我几乎忘了如何用SQL实现这一点,事情是我有一个SQL select语句,如:

SELECT COUNT(*) NAME FROM `SomeTable` WHERE `SomeID` = xxx GROUP BY `Field`

这会返回一个包含一个字段的表和包含数字的许多记录。我想要的是获得这些记录中最大数量的单个值。

7 个答案:

答案 0 :(得分:2)

它应该对你有所帮助。只需使用MAX()函数

SELECT MAX(COUNT(*)) FROM `SomeTable` WHERE `SomeID` = xxx GROUP BY `Field`

答案 1 :(得分:1)

只需添加LIMIT:

SELECT COUNT(`NAME`) AS `NUM` FROM `SomeTable` WHERE `SomeID` = xxx GROUP BY `Field` ORDER BY `NUM`  DESC LIMIT 1

答案 2 :(得分:1)

select max(name) from
(
SELECT COUNT(*) NAME FROM `SomeTable` WHERE `SomeID` = xxx GROUP BY `Field`)a

答案 3 :(得分:1)

SELECT COUNT(*) NAME 
FROM `SomeTable` 
WHERE `SomeID` = xxx 
GROUP BY `Field`
order by NAME desc
limit 1

答案 4 :(得分:0)

  

我想要获得其中最大数量的单个值   记录。

试试这个:

SELECT t1.*
FROM SomeTable t1
(
     SELECT SomeID, Max(Field) MaxField
     FROM SomeTable
     GROUP BY SomeID
) t2 ON t1.SomeID = t2.SomeID AND t1.Field = t2.MaxField
WHERE t1.SomeID = xxx

答案 5 :(得分:0)

如果您只想要针对过滤器获得最高值的单个结果,请使用Max:

SELECT MAX(MyField) NAME 
FROM `SomeTable` 
WHERE `SomeID` = xxx;

或者,如果您希望按另一列分组聚合,则语法如下:

SELECT Name, MAX(MyField) as MaxOfMyField -- Or COUNT(MyField) if you want the Count
FROM `SomeTable` 
WHERE `SomeID` = xxx 
GROUP By Name;

答案 6 :(得分:0)

MAX函数的语法是:

SELECT MAX(expression )
FROM tables
WHERE predicates;

实施例

SELECT MAX(salary) as "Highest salary"
FROM employees;