如果您使用的是 SQL Server 2012,请使用 LAG 函数,如下所示:
SELECT *,
DATEDIFF(HH, TIME, LAG(TIME)
OVER (
ORDER BY TIME))
FROM TABLE1
可以在SQL Fiddle上找到一个工作示例
如果您使用的是 SQL Server 2008,那么您必须像这样进行自联接:
SELECT *,
ROW_NUMBER()
OVER (
ORDER BY TIME)RN
INTO #TEMP1
FROM TABLE1
SELECT t1.*,
DATEDIFF(HH, t1.TIME, t2.TIME)
FROM #TEMP1 t1
LEFT JOIN #TEMP1 t2
ON t1.RN = t2.RN - 1
可以在SQL Fiddle上找到一个工作示例。
编辑
如果您想以hh:mm:ss
格式显示差异,请尝试以下操作:
SELECT *,
ROW_NUMBER()
OVER (
ORDER BY TIME)RN
INTO #TEMP1
FROM TABLE1
SELECT T.EMP_ID,
T.TIME,
T.[IN/OUT],
CASE WHEN DIFF/3600 <10 THEN '0' ELSE '' END + CAST(DIFF/3600 AS VARCHAR(
2)) +
':'
+ CASE WHEN DIFF%3600/60 < 10 THEN '0' ELSE '' END + CAST(DIFF%3600/60 AS
VARCHAR(2))
+ ':00' minutes
FROM (SELECT t1.*,
DATEDIFF(SECOND, t1.TIME, t2.TIME) diff
FROM #TEMP1 t1
LEFT JOIN #TEMP1 t2
ON t1.RN = t2.RN - 1)T
这是SQL Fiddle上的第三个版本