SQL:StartTime列的当前行与EndTime列的上一行之间的差异

时间:2016-06-16 09:30:41

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2

我有一个表,其中有多列,但我需要找到StartTime列的当前行和EndTime列的上一行之间的差异。

示例是以下输出。

Batch Number    Start Time  End Time        Difference

100004          8:00:00     8:03:30        
100005          8:05:00     8:07:00         00:01:30
100006          8:08:40     8:15:00         00:01:40
32141           8:18:00     8:22:45         00:03:00
84230           8:25:10     8:33:42         00:02:25
23444           8:40:00     8:43:00         00:06:18
100001          8:50:00     8:52:00         00:07:00            

我是SQL的新手,正在使用SQL SERVER 2008 R2。

请帮我在Simple Select Query中获取输出。

2 个答案:

答案 0 :(得分:4)

CREATE TABLE #Batches
(
    BatchID     INT,
    StartTime   Datetime,
    EndTime     Datetime,
)
INSERT INTO #Batches
VALUES
(100004,'2016-05-16 08:00:00','2016-05-16 08:03:30'),
(100005,'2016-05-16 08:05:00','2016-05-16 08:07:00'),
(100006,'2016-05-16 08:08:40','2016-05-16 08:15:00'),
(32141 ,'2016-05-16 08:18:00','2016-05-16 08:22:45'),
(84230 ,'2016-05-16 08:25:10','2016-05-16 08:33:42'),
(23444 ,'2016-05-16 08:40:00','2016-05-16 08:43:00'),
(100001,'2016-05-16 08:50:00','2016-05-16 08:52:00')

;WITH CTE AS
(
    SELECT
    BatchID,
    StartTime,
    EndTime,
    ROW_NUMBER() OVER (ORDER BY StartTime) AS Seq
    FROM #Batches
)
SELECT
    b.BatchID,
    b.StartTime,
    b.EndTime,
    CONVERT(VARCHAR(20), DATEADD(SECOND,DATEDIFF(SECOND, bl.EndTime,b.StartTime),0),108) AS Diff,
    DATEADD(SECOND,DATEDIFF(SECOND, bl.EndTime,b.StartTime),0) AS DiffDT
FROM CTE AS b
LEFT OUTER JOIN CTE AS bl ON bl.Seq = b.Seq - 1 -- Last batch   
ORDER BY b.StartTime

答案 1 :(得分:1)

我关注此链接http://blog.sqlauthority.com/2011/11/24/sql-server-solution-to-puzzle-simulate-lead-and-lag-without-using-sql-server-2012-analytic-function/ 这将为您提供几秒钟的差异。

;with cteMain as (
    select *, ROW_NUMBER() over (order by Start_time) sn
      from table)
select m.batch_number, sLag.End_date,  m.Start_time, convert(varchar,DateAdd(Second,DATEDIFF(SECOND, sLag.End_date, m.Start_time),0),108) as time_diff
  from cteMain as m LEFT OUTER JOIN cteMain AS sLag ON sLag.sn = m.sn-1
order by m.batch_number