一行上的T-SQL多日期时间差异

时间:2014-10-16 02:45:29

标签: sql sql-server

使用SQL Server(T-SQL),我有两个表:

tblTrial

TrialID (PK) int
TrialDate
...

tblLaps

LapID (PK) int
TrialID (FK) int
LapNumber int
LapStart smalldatetime
...

对于TrialID = 1,有四个Lap行:

LapID  TrialID   LapNumber    LapStart
  1       1          1         t1 (some smalldatetime value)
  2       1          2         t2
  3       1          3         t3
  4       1          4         t4

我想显示SQL,以便每次试用时只显示一行,并且它有时间差异。

例如,TrialID = 1的行可能如下所示:

Trial#   1stLap   2ndLap   3rdLap
---------------------------------
   1       3min     4min     5min

其中1stLap是时间差t2-t1,2ndLap是t3-t2,3rdLap是t4-t3。

如何在SQL语句中将所有内容都放在一行?

由于

2 个答案:

答案 0 :(得分:1)

对于以分钟为单位的时差,你可以这样做:

with laps as  -- First CTE table to join every lap with the next lap to get end time
(
select TrialID,t1.LapID, datediff(mi,t1.LapStart, t2.LapStart ) as Lap
from tblLaps t1
join tblLaps t2
on   t1.LapID = t2.LapID - 1  and t1.TrialID = t2.TrialID
)
select TrialID, 
       max(case t1.LapID when 1 then Lap else null end) as [1stLap],
       max(case t1.LapID when 2 then Lap else null end) as [2ndLap],
       max(case t1.LapID when 3 then Lap else null end) as [3rdLap],
from   laps
group  by TrialID

如果您希望秒数不同,请使用datediff(ss,startdate , enddate ),这是datediff document

答案 1 :(得分:1)

select
        t.TrialID
      , datediff(minute, max(case when LapNumber = 1 then LapStart end) , max(case when LapNumber = 2 then LapStart end) ) lap1_2
      , datediff(minute, max(case when LapNumber = 2 then LapStart end) , max(case when LapNumber = 3 then LapStart end) ) lap2_3
      , datediff(minute, max(case when LapNumber = 3 then LapStart end) , max(case when LapNumber = 4 then LapStart end) ) lap3_4
from tblTrial as t
inner join tblLaps as l on t.TrialID = l.TrialID
group by
        t.TrialID

请参阅this sqlfiddle demo