2010-08-23 78 views
2

我有这个模式的表:帮助与SQL查询

的DeviceID INT
RoomID INT
DateInstalled日期时间

表的数据的样本是这样的:

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 

任何帮助将不胜感激,

感谢。

+0

你有过表结构的任何控制? – AllenG 2010-08-23 18:21:44

回答

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 
+0

我通过删除ISNULL来使用它。 Thanks Fosco .. – Anon4this 2010-08-23 18:36:21