2016-12-04 135 views
-2

我需要您的幫助。我使用sql server 2012. 此查詢是針對日誌應用程序的。 我有一個這樣的表格:T sql查詢。確定日期列中的開始日期/結束日期

這是一個帶有2個請求標識符的示例,這裏是我想要獲得的結果。

我已經完成了整個週末,仍然沒有找到解決方案。 我嘗試了SQL Server 2012的滯後和引導功能,但它不起作用。

IF OBJECT_ID('tempdb..#test', 'U') IS NOT NULL 
DROP TABLE #test; 

CREATE TABLE #test 
(
    requestid INT, 
    eventdate DATETIME, 
    eventname VARCHAR(20) 
); 

INSERT #test 
(
    requestid, 
    eventdate, 
    eventname 
) 
VALUES 
(46444, '2016/08/08 10:20:33.000', 'OPENED'), 
(46444, '2016/08/08 10:33:10.000', 'REVIEWED'), 
(46444, '2016/08/08 11:09:55.000', 'OPENED'), 
(46444, '2016/08/08 11:32:41.000', 'REVIEWED'), 
(46444, '2016/08/08 11:39:01.000', 'CLOSED'), 
(46444, '2016/08/08 15:00:04.000', 'OPENED'), 
(46444, '2016/08/08 15:17:40.000', 'REVIEWED'), 
(46444, '2016/08/08 15:29:36.000', 'OPENED'), 
(46444, '2016/08/08 15:31:34.000', 'REVIEWED'), 
(46444, '2016/08/08 15:36:37.000', 'CLOSED'), 
(46444, '2016/08/08 17:04:27.000', 'OPENED'), 
(46445, '2016/08/10 09:00:00.000', 'OPENED'), 
(46445, '2016/08/11 01:33:10.000', 'REVIEWED'), 
(46445, '2016/08/12 15:36:37.000', 'CLOSED'); 

select * 
from #test 

結果

requestid eventdate   eventname CLOSEDDate  CLOSEDEventname 
46444 2016-08-08 10:33:10.000 REVIEWED 2016-08-08 11:39:01.000 CLOSED 
46444 2016-08-08 15:17:40.000 REVIEWED 2016-08-08 15:36:37.000 CLOSED 
46445 2016-08-11 01:33:10.000 REVIEWED 2016-08-12 15:36:37.000 CLOSED 
+1

請編輯您的問題並提供列的邏輯。 –

回答

1

我可以看到你彷彿想。對於每個關閉日期,您需要最近的關閉日期。您可以通過只枚舉關閉指定一個組,然後彙總爲此在:

select requestid, 
     min(case when eventname = 'REVIEWED' then eventdate end) as eventdate, 
     'REVIEWED' as event, 
     max(eventdate) as closedate, 
     'CLOSED' as closedeventname 
from (select t.*, 
      sum(case when eventname = 'CLOSED' then 1 else 0 end) over (partition by requestid order by eventdate desc) as grp 
     from #test t 
    ) t 
group by requestid, grp; 
Having min(case when eventname = 'REVIEWED' then eventdate end) is not null 

我敢肯定,這會產生你想要的輸出。如果您未能在問題中指定您需要的其他規則,我會強烈建議您詢問另一個問題並提供更好的解釋。

+0

Yeees !!!!!正是我想要的。非常感謝John和Gordon – Lidou123

相關問題