2016-07-01 4 views
0

の最初のインスタンスInspectionDateに(例えば除く占有>空いている>占有>占有>空いている>空いているが、空いているなど、>空いている>空いているか、空いている>占有または空いている)TSQL:私は<code>Occupancy</code>が<code>Occupancy</code>の最後のインスタンスが空いていると連続関係に<code>Room_ID</code>の生活中に中断することなくなっているので、場合にのみ、空いている最初の時間を報告しているすべての<code>Room_IDs</code>を取得する必要がありますX

これは私が一例として使用しています単純化された表は次のとおりです。

Room_Id inspection_ID Occupancy InspectionDate 
---------------------------------------------------- 
    1  11    vacant  5/15/2015 
    1  12    occupied  5/21/2015 
    1  13    vacant  9/19/2015 
    1  14    occupied  1/16/2016 
    2  21    vacant  3/25/2015 
    2  22    occupied  8/27/2015 
    2  23    occupied  4/17/2016 
    3  31    occupied 12/12/2015 
    3  32    occupied  3/22/2015 
    3  33    vacant  2/2/2016 
    3  34    occupied  3/24/2016 
    4  41    occupied  4/17/2015 
    4  42    occupied 11/12/2015 
    4  43    occupied 12/22/2015 
    4  44    vacant  2/2/2016 
    4  45    vacant  3/24/2016 
    5  45    vacant  3/24/2015 
    5  45    vacant  3/24/2016 

私の結果は次のようになります。

Room_Id inspection_ID Occupancy InspectionDate 
--------------------------------------------------- 
    4  41    occupied  4/17/2015 
    4  42    occupied 11/12/2015 
    4  43    occupied 12/22/2015 
    4  44    vacant  2/2/2016 
    4  45    vacant  3/24/2016 
    5  45    vacant  3/23/2015 
    5  45    vacant  3/24/2016 

それが十分明確でない場合は私に知らせてください。 (または何も存在しないダミー日付)

+1

[TSQL:特定のパーティションのトップレコード(条件付き)]の可能な複製(http://stackoverflow.com/questions/38112133/tsql-the-top-records-of-a-given-partition-conditional ) –

+0

@AlexKudryashevは、IDのすべてのインスタンスについて2つの最後のレコードが空いている場合に、閉じることはできますが、まったく同じではありません。これはFTVをチェックします –

答えて

0
select * from T where Room_ID in ( 
    select Room_ID from T 
    group by Room_ID 
    having 
      coalesce(
       max(case when occupancy = 'occupied' then InspectionDate end), 
       cast('19000101' as date) 
     ) < 
      min(case when occupancy = 'vacant' then InspectionDate end) 
); 

having条件は、その後vacantsのすべてが後occupiedsより見えるtrueの場合

ここでの分析を使用して、同じアプローチがあります:

select * from 
( 
    select *, 
     max(case when occupancy = 'occupied' then InspectionDate end) 
      over (partition by Room_ID, occupancy) as max_o 
     min(case when occupancy = 'vacant' then InspectionDate end) 
      over (partition by Room_ID, occupancy) as min_v 
    from T 
) t 
where max_o < min_v or max_o is null and max_v is not null; 

計画を確認し、どちらが良いかを確認します。

関連する問題

 関連する問題