简体   繁体   English

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

[英]MySQL Select only rows with Max Value on a Column

I use the following code to list the jid and count. 我使用下面的代码列出了jid和count。

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

在此处输入图片说明

but I also want to show the jid and the max(jidtime),which is jid:4 jidtime:6 但我还想显示jid和max(jidtime),即jid:4 jidtime:6

I tried, but fail. 我尝试过,但是失败了。 Need some help... 需要一些帮助...

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

You would do this with order by and limit : 您可以通过order bylimit来执行此操作:

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

This takes the results, orders them by the second column, and then limits the query to the first row (which should have the highest value). 这将获取结果,按第二列对其进行排序,然后将查询限制为第一行(应具有最高值)。

Use a subquery in an in-clause: 在子句中使用子查询:

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

Or just order by descending, and limit, which should be faster: 或者只是按降序排列,然后限制,这应该更快:

Select * from Application order by jidtime desc limit 1

i think you have two options. 我认为您有两种选择。 i cant give the excat (tested) code becasue i dont have a mssql right now. 我无法提供exat(经过测试)的代码,因为我现在没有mssql。

one is something with rank, i dont know the correct code now, but it should be like 一个是有等级的东西,我现在不知道正确的代码,但是应该像

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

the second option is with a subquery. 第二个选项是子查询。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM