SQL Server查找开始时间和结束时间之间的时间段

时间:2014-04-09 20:19:19

标签: sql sql-server

SQL Server,如何从调度表中找到时隙,比如我需要输出第一列的结束时间和下一列的开始时间?

 select 
    s, e,
    Max(cid)as c_id,
    ROW_NUMBER()OVER(order by CAST(s as datetime)) as row_id
 from classroom 
 where Room like '3310' and Days like '%T%' 
 group by s,e
 order by CAST(s as datetime)

例如:

s       e       c_id    row_id
------- ------- ------- ------
9:30    10:45   235     1
11:00   12:15   236     2
12:30   13:45   238     3
14:00   15:15   1415    4
15:30   16:45   273     5
17:00   18:15   270     6

我需要输出

10:45-11:00
12:15-12:30
13:45-14:00

由于

2 个答案:

答案 0 :(得分:2)

您可以将数据插入临时表,然后查询该临时表

select s,e,Max(cid)as c_id,
    ROW_NUMBER()OVER(order by CAST(s as datetime))as row_id 
into #t
from classroom 
where Room like '3310' and Days like '%T%' 
group by s,e 
order by CAST(s as datetime)


select t1.e, t2.s
from #t t1 
    INNER JOIN #t t2 on t1.row_id + 1 = t2.row_id

答案 1 :(得分:0)

如果你想知道只有当一个班级完成和下一个班级之间的时间差距加上where t2.s > t1.e给Abhi的答案时。如果您需要最小尺寸的广告位,例如15分钟,请使用where DATEDIFF(mi, t1.e, t2.s) > 15