2016-05-20 6 views
2

Ich muss alle Room_IDs, wo die Status sind vakant gemeldet, und dann zu einem späteren Zeitpunkt, nur besetzt.TSQL: bedingte Gruppe von Abfrage

Dies ist eine vereinfachte Tabelle I als Beispiel verwenden:

**Room_Id Status Inspection_Date** 
    1  vacant  5/15/2015 
    2  occupied 5/21/2015 
    2  vacant  1/19/2016 
    1  occupied 12/16/2015 
    4  vacant  3/25/2016 
    3  vacant  8/27/2015 
    1  vacant  4/17/2016 
    3  vacant  12/12/2015 
    3  occupied 3/22/2016 
    4  vacant  2/2/2015 
    4  vacant  3/24/2015 

wie dies Mein Ergebnis soll aussehen:

**Room_Id Status Inspection_Date** 
    1  vacant  5/15/2015 
    1  occupied 12/16/2015 
    1  vacant  4/17/2016 
    3  vacant  8/27/2015 
    3  vacant  12/12/2015 
    3  occupied 3/22/2016 

Antwort

4

Hier ist eine Option exists mit einem correlated subquery mit:

select * from yourtable t 
where exists (
    select 1 
    from yourtable c 
    where c.room_id = t.room_id 
    group by c.room_id 
    having min(case when status = 'vacant' then inspection_date end) < 
     max(case when status = 'occupied' then inspection_date end) 
) 
0

Versuchen Sie, diese

;WITH cte 
    AS (SELECT *, 
       Row_number()OVER(partition BY [room_id] ORDER BY [inspection_date])rn,     FROM YOurtable) 
SELECT room_id, 
     status, 
     [inspection_date] 
FROM cte a 
WHERE EXISTS (SELECT 1 
       FROM cte b 
       WHERE a.room_id = b.room_id 
         AND b.rn = 1 
         AND b.status = 'vacant') 
     AND EXISTS(SELECT 1 
        FROM cte c 
        WHERE a.room_id = c.room_id 
         AND c.status = 'occupied') 
0

SQLFiddle Demo

select * From table1 where room_id in(
SELECT room_id 
FROM 
    (SELECT lag(inspection_date,1,NULL) 
      over (partition BY room_id 
        ORDER BY status DESC) 
     AS prev_Inspection_date, 
    t.* 
     FROM 
     (SELECT room_id, 
      CASE WHEN status='vacant' THEN min(inspection_date) ELSE max(inspection_date) END 
     AS inspection_date,                        status 
     FROM table1 
     GROUP BY room_id,    status 
     ) t 
    ) s 
WHERE prev_Inspection_date < inspection_date 
    AND prev_Inspection_date IS NOT NULL)