2016-05-20 13 views
2

Statusが空いていると報告されたすべてのRoom_IDsを取得する必要があります。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

ここcorrelated subqueryexistsを使用して一つの選択肢です:

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) 
をお試しください0