如何从记录中计算日期范围

时间:2010-08-23 18:18:40

标签: sql

我有一个包含此架构的表:

DeviceID int
RoomID int
DateInstalled datetime

表格数据的样本如下:

DeviceID   RoomID   DateInstalled
0001       Room1    1/1/2000  
0002       Room1    1/1/2000  
0001       Room2    2/1/2000  

我需要构建一个查询,它会告诉我每个设备在特定房间的日期范围。类似的东西:

DeviceID   RoomID   From Date    To Date
0001       Room1    1/1/2000     1/31/2000 
0001       Room2    2/1/2000     NULL 
0002       Room1    1/1/2000     NULL

1 个答案:

答案 0 :(得分:1)

试一试:

select a.DeviceID, a.RoomID, a.DateInstalled as fromDate, 
    ISNULL((select DATEADD(day,-1,MIN(DateInstalled)) from myTable
            where DeviceID = a.DeviceID
            and RoomID <> a.RoomID
            and DateInstalled > a.DateInstalled),'') as toDate
from myTable a