tags:

views:

48

answers:

1

Hi,

I have a table with this schema:

DeviceID int
RoomID int
DateInstalled datetime

A sample of the table's data looks like:

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

I need to build a query that will give me the date range each device was located on a specific room. Something like:

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

Any help will be appreciated,

Thanks.

+1  A: 

Give this a shot:

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
Fosco
I used this by removing the ISNULL.Thanks Fosco..
Anon4this