基于行和列的约会

时间:2017-08-16 11:03:06

标签: sql sql-server tsql

我有下表

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查询?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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