按最高/最大值分组并计算差异

时间:2017-05-02 05:34:44

标签: mysql sql group-by max sql-function

这是针对Oracle服务器上的数据运行的MYSQL / SQL。我有一个SQL表,存储数据如下:

{IMPORTID Created  IMPORTREQUESTID    STARTDATE       ENDDATE
1156     04/21/2017 (12 AM)    63833           4/23/2017 18:18 4/23/2017 18:19
1156     04/21/2017 (12 AM)    63833           4/23/2017 18:18 4/23/2017 18:18
1156     04/21/2017 (12 AM)   63832           4/23/2017 17:56 4/23/2017 17:57
1156     04/21/2017 (12 AM)    63832           4/23/2017 17:56 4/23/2017 17:57
1156     04/21/2017 (12 AM)   63832           4/23/2017 17:56 4/23/2017 17:57}  

我希望查询遍历表格并找到任何给定IMPORTID的HIGHEST或MAX IMPORTREQUESTID和最大ENDDATE。然后,一旦找到包含最大值的行,就计算任何给定IMPORTID的CREATED和max(ENDDATE)之间的差异。同样,我只想将最大IMPORTREQUESTID和ENDDATE绑定到给定的IMPORTID。 (IMPORTID将有几行具有不同的IMPORTREQUESTIDS)

因此,对于上面给定的数据,我的查询应该只返回1行,如下所示:

{IMPORTID Created  IMPORTREQUESTID    STARTDATE       ENDDATE         DIFF
1156    04/21/2017 12 AM    63833  4/23/2017 18:18  4/23/2017 18:19  **6:19**}

因此,在这种情况下,它发现IMPORTREQUESTID 63833是最高值,而18:19的最终结束时间最长。然后它选择了该行并计算了created和ENDDATE之间的差异。

这是我到目前为止的查询:

     SELECT ImportID 
 ,A.created
 ,IMPORTSTATUS 
 ,IMPORTCANONICALTYPE  
 , to_char(StartDate,'MM/DD/YYYY HH24:MI') StartDate 
 , to_char(EndDate,'MM/DD/YYYY HH24:MI') EndDate  
 , ((A.created-A.Enddate)*60*24) as MinDiff 
 , ImportRequestID

FROM (SELECT DISTINCT importrequestpartdone.ImportID
,importrequestpartdone.IMPORTCANONICALTYPE 
 ,importrequestpartdone.IMPORTSTATUS 
 ,importrequestpartdone.ImportRequestID 
 , importrequestpartdone.StartDate 
 , importrequestpartdone.EndDate 
,import.created
     From import,baywatchnosnap.importrequestpartdone@db1 
 where contextid=10114
and import.id=importrequestpartdone.importid
and importrequestpartdone.importstatus='2I') A

返回所有行。我只想要如上所示的最大值。因此,每个IMPORTID应该只返回1行。

1 个答案:

答案 0 :(得分:0)

即使我不明白你是如何达到6:19的差异,因为差异仅为1分钟

但试试这个: -

SELECT importrequestpartdone.ImportID 
 ,import.created
 ,importrequestpartdone.IMPORTSTATUS 
 ,importrequestpartdone.IMPORTCANONICALTYPE  
 , to_char(StartDate,'MM/DD/YYYY HH24:MI') StartDate 
 , to_char(EndDate,'MM/DD/YYYY HH24:MI') EndDate  
 , ((A.created-A.Enddate)*60*24) as MinDiff 
 , importrequestpartdone.ImportRequestID

FROM baywatchnosnap.importrequestpartdone@db1
inner join

(SELECT importrequestpartdone.ImportID
 ,max(importrequestpartdone.ImportRequestID) as max_req_id
 , max(importrequestpartdone.EndDate) as max_end
     From import,baywatchnosnap.importrequestpartdone@db1  
 where contextid=10114
and import.id=importrequestpartdone.importid
and importrequestpartdone.importstatus='2I'
group by importrequestpartdone.ImportID ) A

on a.ImportID=importrequestpartdone.ImportID and a.max_req_id=importrequestpartdone.ImportRequestID
and a.max_end=importrequestpartdone.EndDate

inner join
import
on import.id=importrequestpartdone.importid
where contextid=10114
and importrequestpartdone.importstatus='2I';