选择后返回MAX

时间:2014-12-02 01:00:49

标签: select max

我是SQL Queries的新手,我遇到的问题是获取Max Speed of Column Speedo是我当前的查询

SELECT 
tblVehicle.Rego
,tbljob.Speedo 
,tbljob.DateEntered
from tblJob
INNER JOIN tblVehicle 
 on tbljob.Vehicle_ID = tblVehicle.ID
   where JobType_ID = 2
   order by Rego

哪个输出

Rego    Speedo  DateEntered
000JKC  147729  2010-05-10 10:56:55.040
000JKC  150145  2010-06-02 13:57:15.470
000JKC  169553  2011-01-06 12:24:09.143
000JKC  155149  2010-07-21 14:58:20.777
000JKC  157882  2010-09-17 16:39:48.480
000JKC  165660  2010-11-29 08:20:39.453
000JKC  164339  2010-11-18 16:19:19.213
000JKC  155149  2010-08-11 06:16:28.180
000RQD  65  2011-11-21 09:27:31.693
000RQD  6978    2012-03-06 15:18:06.987
000RQD  6766    2012-02-24 13:28:47.603
000RQD  12130   2012-08-28 09:29:18.027
000RQD  12145   2012-08-27 14:57:17.330
000RQD  21550   2013-04-15 19:30:30.160
000RQD  23640   2013-05-22 16:16:33.880

现在我只想要每个Rego的MAX(Speedo)。

2 个答案:

答案 0 :(得分:0)

MAX()函数返回所选列的最大值。

SELECT 
tblVehicle.Rego
, MAX( tbljob.Speedo )
,tbljob.DateEntered
from tblJob
INNER JOIN tblVehicle 
 on tbljob.Vehicle_ID = tblVehicle.ID
   where JobType_ID = 2
   order by Rego

答案 1 :(得分:0)

您需要使用GROUP BY

SELECT 
tblVehicle.Rego
,MAX(tbljob.Speedo) as MaxSpeedo
,MAX(tbljob.DateEntered) as MaxDate
from tblJob
INNER JOIN tblVehicle 
 on tbljob.Vehicle_ID = tblVehicle.ID
   where JobType_ID = 2
   order by Rego
GROUP BY Rego

注意:如果Speedo被收回,这可能无法达到您想要的效果,并且最后一个日期没有Speedo的最大值。在这种情况下,您将看到最大速度和最大日期,但它们来自不同的行。