Home Forums SQL Server 2005 Development 2008 R2 Adding a columm with time differences between transactions per employee/date RE: 2008 R2 Adding a columm with time differences between transactions per employee/date

  • @david-2 thank you but it didn't work and run for almost 1 hours, my intentions were to get a time comparison between the last record from a same employee number and from a time perspective for if the was 0800 and next was 0900 the time difference was 1 hour, another example if it was 1005 next was 1020 then the difference was 20 minutes. The sample I gave was misunderstood - so I provided the true fields below.

    Here is an example of what I was hoping to get back from the rows off data

    TLR_Br_Num|TLR_Emp_Num|TLR_Trn_Dt|TLR_Trn_Tm|Date_Time|RowNum

    00001|12345|01052015|0820|20150105 08:20:00|0

    00001|12345|01052015|0824|20150105 08:24:00|4 a difference of 4 minutes from the last transaction

    00001|23456|01052015|0825|20150105 08:25:00|0 New Employee

    00001|23456|01052015|0830|20150105 08:30:00|5

    SQL Query

    ;WITH cte_TELLER(TLR_Br_Num,TLR_Emp_Num,TLR_Trn_Dt,TLR_Trn_Tm, Date_Time,RowNum)

    AS (

    SELECT TLR_Br_Num,TLR_Emp_Num,TLR_Trn_Dt,TLR_Trn_Tm,

    CAST(CONVERT(char(10),TLR_Trn_Dt,120)+' '+STUFF(TLR_Trn_Tm,3,0,':') as datetime) AS Date_Time,

    ROW_NUMBER() OVER (PARTITION BY TLR_Br_Num,TLR_Emp_Num,TLR_Trn_Dt,TLR_Trn_Tm ORDER BY TLR_Trn_Tm ASC)AS RowNum

    FROM dbo.TLR

    WHERE TLR_BR_Num = '00001' and TLR_Mo = ' 1' and TLR_Yr = '2015'

    )

    SELECT a.TLR_Br_Num,a.TLR_Emp_Num,a.TLR_Trn_Dt,a.TLR_Trn_Tm,

    ISNULL(CAST(STUFF(CONVERT(char(5),DATEADD(minute,DATEDIFF(minute,b.TLR_Trn_Tm,a.TLR_Trn_Tm),0),114),3,1,'') as int),0)

    FROM cte_TELLER a LEFT JOIN cte_TELLER b ON b.TLR_Br_Num = a.TLR_Br_Num AND b.TLR_Emp_Num = a.TLR_Emp_Num

    AND b.TLR_Trn_Dt = a.TLR_Trn_Dt AND b.TLR_Trn_Tm = a.TLR_Trn_Tm AND b.RowNum = a.RowNum - 1

    ORDER BY a.TLR_Trn_Dt ASC,a.TLR_Emp_Num ASC