计算SQL Server中表的一列中两个连续行的时间差

时间:2015-09-21 07:29:59

标签: sql-server

我有一个像

这样的查询
table1
____________________________________________________________________
UniqueID   TicketNumber   Action                    Date
--------------------------------------------------------------------
 1         123456         Dependency Occured        3/25/2015 7:40:39 AM
 2         123456         Tech Support requested    3/25/2015 10:00:47 AM
 3         123456         Tech Support Given        3/25/2015 11:30:40 AM
 4         123456         Dependency Occured        3/25/2015 02:30:40 PM
 5         123456         Tech Support Given        3/25/2015 03:30:40 PM

对于相同的 TicketNumber ,在给定时间执行各种操作。现在我必须找到' Dependency Occured '的总时间。 因此,依赖性发生的行动日期必须从它下面的行中减去,因为我必须计算发生的依赖性总时间。 像第一排 - 第二排给出 2小时20分钟。 第4行 - 第5行给出 1小时。 所以总依赖性是 3小时20分钟。

提前致谢。

1 个答案:

答案 0 :(得分:3)

假设您使用sql server 2012或更高版本,可以使用lead来解决此问题:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:choiceMode="singleChoice"
    android:divider="@android:color/transparent" android:dividerHeight="0dp"
    android:background="#ffffff" tools:context=".NavigationDrawerFragment"
    android:listSelector="#eeeeee" />

see fiddle here

2005/2008年,您将不得不使用子查询而不是铅:

;with cte1 as 
(
select  TicketNumber, 
        Action, 
        date,
        lead(date) over(partition by TicketNumber order by date) as nextActionDate
from table1
), cte2 as
(
select TicketNumber, 
       sum(datediff(minute, date, nextActionDate)) as timeOfDependencyOccured
from cte1 
where Action = 'Dependency Occured'
group by TicketNumber
)

select TicketNumber, 
       cast(timeOfDependencyOccured / 60 as varchar(2)) + ':' + 
       cast(timeOfDependencyOccured % 60 as varchar(2))
from cte2

see fiddle here