2014-04-09 161 views
0

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

您可以在臨時表中插入數據,然後查詢該臨時表

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 
0

如果您想知道只有在完成一節課和下一節課之間存在時間差距,請將where t2.s > t1.e添加到Abhi的答案中。如果您需要最小插槽大小,例如15分鐘,請使用where DATEDIFF(mi, t1.e, t2.s) > 15

相關問題