2017-08-16 86 views
0

我有以下表行和基於列DATEDIFF

ROW  StartDT     EndDT      USERID  LOCATION 
---------------------------------------------------------------------------------- 
R1  2017-05-24 15:39:36.000 NULL      1   Loc1 
R2  2017-05-24 11:10:26.000 2017-05-24 11:13:43.000 2   Loc1 
R3  2017-05-24 11:57:50.000 2017-05-24 12:00:04.000 3   Loc1 

輸出邏輯應該

For location = Loc1, datediff(minutes, (R2.EndDT - R3.StartDT)) 

如果EndDT具有null值那麼結果應顯示NULL

如何爲此編寫SQL查詢?

+0

最新的SQL服務器版本有LEAD,LAG – Serg

+0

選擇R2行和R3行,但不是R1的邏輯是什麼? –

回答

0

試試這個

;With cte([ROW],StartDT,EndDT, USERID ,LOCATION) 
AS 
(
SELECT 'R1','2017-05-24 15:39:36.000', NULL      ,1 , 'Loc1' UNION ALL 
SELECT 'R2','2017-05-24 11:10:26.000', '2017-05-24 11:13:43.000' , 2, 'Loc1' UNION ALL 
SELECT 'R3','2017-05-24 11:57:50.000', '2017-05-24 12:00:04.000' , 3, 'Loc1' 
) 
SELECT [Row], 
     Startdt, 
     Enddt, 
     Userid, 
     Location, 
     CASE 
     WHEN Enddt IS NOT NULL THEN Datediff(minute, Enddt, Leadstartdt) 
     ELSE Enddt 
     END AS DiffInMinutes 
FROM (SELECT *, 
       Lead(Startdt) 
       OVER( 
        ORDER BY [Row]) AS LeadStartDT 
     FROM Cte)Dt WHERE Dt.LOCATION='Loc1' 

結果

Row startdt    enddt     userid location DiffInMinutes 
------------------------------------------------------------------------------------------- 
R1 2017-05-24 15:39:36.000 NULL     1  Loc1   NULL 
R2 2017-05-24 11:10:26.000 2017-05-24 11:13:43.000 2  Loc1   44 
R3 2017-05-24 11:57:50.000 2017-05-24 12:00:04.000 3  Loc1   NULL 
0

這應該工作:

with Q as 
(
    select top 1 *, cast(null as int) nxt1, cast(null as int) nxt2 
     from YourTable order by row 
     union all 
      select T.*, Q1.row, Q2.row from YourTable T 
       cross apply 
       (
        select * from YourTable T1 where T1.row - 1 = T.row 
       ) Q1 

       cross apply 
       (
        select * from YourTable T1 where T1.row - 2 = T.row 
       ) Q2 
) 


select 
    Q.row, Q.startDT, Q.endDT, Q.userid, Q.location, 

    case when T1.endDT is not null 
     then datediff(minute, T1.endDT, T2.startDT) 
     else null 
    end as diff_in_minutes 

    from Q  
    inner join YourTable T1 on Q.nxt1 = T1.row 
    inner join YourTable T2 on Q.nxt2 = T2.row 

Q是一個遞歸查詢,其中基本情況是第一行和遞歸大小寫是接下來的兩行(相對於行ID)。

結果:

row startDT     endDT     userid location diff_in_minutes 
----- ----------------------- ----------------------- ------- --------- --------------- 
1  2017-05-24 11:10:26.000 2017-05-24 11:13:43.000 1  1   44 

Rextester Demo