2010-08-23 67 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