检索具有最大值的所有行

时间:2012-03-15 10:50:50

标签: mysql sql

我有这样的查询:

SELECT state AS ls,count(*) AS total, max(sales) AS ye FROM TABLE
GROUP BY state

然后我得到以下结果:

A total ye
----------
a  22   23
b  23   23
c  24   21
d  25   21

但我想只显示最大值为ye的状态,即:

A total ye
----------
a  22   23
b  23   23

4 个答案:

答案 0 :(得分:4)

您可以使用HAVING子句,它类似于WHERE仅在检索完所有数据后执行。您可以在分组后指定它:

select state as ls,count(*) as total ,max(sales) as ye from  table    
group by state
having count(*) = max(sales)

答案 1 :(得分:3)

尝试:

select state as ls,count(*) as total, max(sales) as ye from  table    
group by state
having max(sales) = (select max(sales) from table)

答案 2 :(得分:2)

select state as ls,count(*) as total ,max(sales) as ye from  table    
where sales = (select max(sales) from table)
group by state

答案 3 :(得分:1)

尝试此查询:

select * from (select state as ls,count(*) as total ,max(sales) as ye from  table    
group by state)temp HAVING max( ye );