Find the time difference between two consecutive rows in the same table in sql

前端 未结 5 1410
广开言路
广开言路 2020-12-30 15:21

I\'m stuck. I\'ve looked for an answer, but can\'t seem to find subtracting time in the same table from two different rows of the same table that fits. I\'m having a difficu

相关标签:
5条回答
  • 2020-12-30 15:30

    I have solved this for similar problems and it need not be that the rows even be sorted:

    select t1.EmpID, t1.TimeIn, t1.TimeOut, 
           datediff(minute, max(t2.TimeOut), t1.TimeIn) as minutes
    from timesheet t1 left join timesheet t2 on t1.EmpID = t2.EmpID 
           and t2.TimeOut < t1.TimeIn
    group by t1.EmpID, t1.TimeIn, t1.TimeOut
    

    Let me know if this works.

    Here is a sql fiddle: http://sqlfiddle.com/#!3/89a43/1

    0 讨论(0)
  • 2020-12-30 15:33

    try something like that:

    select *, DATEDIFF(minute, (
        select max(b.TimeOut)
        from TIMESHEET as b where a.EmpID=b.EmpID and b.ROW<a.ROW
        ), a.TimeIn
    ) as diff
    from TIMESHEET as a
    
    0 讨论(0)
  • 2020-12-30 15:53

    Since you have mentioned PARTITION clause, given below is a version using that clause (haven't tested for syntax, but it should give you the idea)

    ;WITH EmpData AS
    (
        SELECT  EmpID, 
                    TimeIn, 
                    TimeOut,
                    ROW_NUMBER() OVER(PARTITION BY EmpId ORDER BY TimeIn) Position
           FROM EmployeeTime 
    )
    SELECT a.*
             a.TimeOut-b.TimeIn OutTIme 
       FROM EmpData a  LEFT JOIN EmpData b
             ON a.EmpId = b.EmpId
          AND a.Position-1  = b.Position  
    
    0 讨论(0)
  • 2020-12-30 15:54
    WITH rows AS
    
    (
    
    SELECT  *, ROW_NUMBER() OVER (ORDER BY EmpID) AS rn        
    FROM    TimeSheet         
    )
    
    SELECT mc.EmpID, DATEDIFF(MINUTE, mc.TimeIn, mp.TimeOut) as TimeDiffInMinutes
    FROM    rows mc JOIN    rows mp ON   mc.rn = mp.rn-1
    
    0 讨论(0)
  • 2020-12-30 15:55

    While looping through a cursor is normally a dismal way to do things both from a performance perspective and in terms of provability and maintainability, in cases like this, where you are traversing the edges of a directed acyclic graph, a loop can be just what the doctor ordered.

    In my opinion you have two good options when using versions of SQL Server that do not support LEAD OVER PARTITION.

    • loop using a cursor in T-SQL
    • loop using a LINQ enumerable in application code

    Whether it's worthwhile marshalling all the life-support for LINQ depends on what else you're doing.

    The question is tagged sql-server-2008 which does not support LEAD OVER PARTITION, and on that platform in the absence of supporting indexes it is a great deal faster with a much smaller working set to use a cursor.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题