MySQL仅选择列上具有“最大值”的行

时间:2014-03-11 22:34:51

标签: mysql sql

我使用以下代码列出jid和count。

Select jid,count(jid) as jidtime 
From Application
Group by jid;

enter image description here

但我也想展示jid和max(jidtime),这是jid:4 jidtime:6

我试过,但失败了。需要一些帮助...

Select jid, max(jidtime) 
From (Select jid,count(jid) as jidtime From Application
Group by jid) AS T;

3 个答案:

答案 0 :(得分:0)

您可以使用order bylimit执行此操作:

Select jid, count(jid) as jidtime 
From Application a
Group by jid
Order by count(jid) desc
Limit 1;

这将获取结果,按第二列对它们进行排序,然后将查询限制为第一行(应具有最高值)。

答案 1 :(得分:0)

在子句中使用子查询:

Select * from Application
WHERE jidtime IN (Select Max(jidtime) From Application)

或者只是按降序排序,并限制,这应该更快:

Select * from Application order by jidtime desc limit 1

答案 2 :(得分:0)

我认为你有两种选择。我不能给出令人兴奋的(测试过的)代码,因为我现在没有mssql。

一个是排名的东西,我现在不知道正确的代码,但它应该像

 select jid, count(jid) OVER (PARTITION BY jid order by count(jid)) 
 from Application 
 group by jid 

第二个选项是子查询。

select jid, count(jid) as jidtime 
from Application
group by jid
having count(jid) = (select max(count(jid) 
                         from Application 
                         group by jid
                     )