2016-05-20 82 views
2

我需要獲得所有Room_IDs,其中Status報告爲空,然後僅在以後的日期佔用。TSQL:條件組查詢

這是我使用作爲實例的簡化表:

**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 

我的結果應該是這樣的:

**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 

回答

4

下面是使用existscorrelated subquery一個選項:

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

試試這個

;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)