2017-05-02 84 views
-1

這是針對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} 

我想查詢要經過此表並找到最高或MAX IMPORTREQUESTID和最大ENDDATE對於任何給定IMPORTID。然後計算任何給定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的最高值和THEN最後時間是最高值。然後它選擇了該行並計算了創建和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,[email protected] 
where contextid=10114 
and import.id=importrequestpartdone.importid 
and importrequestpartdone.importstatus='2I') A 

這將返回所有行。我只想要如上所示的最大值。所以,每個IMPORTID,只應該返回1行。

+1

你能解釋一下你怎麼到達在'6:19'的差異處爲您的樣本數據? –

+0

我們應該忽略「StartDate」,「EndDate」還是兩者的時間分量? – toonice

+0

更小的'ImportRequestID'可以有更近期的'EndDate',反之亦然? – toonice

回答

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 [email protected] 
inner join 

(SELECT importrequestpartdone.ImportID 
,max(importrequestpartdone.ImportRequestID) as max_req_id 
, max(importrequestpartdone.EndDate) as max_end 
    From import,[email protected] 
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';