2016-07-01 2 views
0
내가 얻을 필요가

의 첫 번째 인스턴스의 모든 Occupancy가 빈 처음보고 된 Room_IDs, 그래서 오직 Occupancy의 마지막 인스턴스가 비어 연속적 관계에 Room_ID의 수명 동안 중단없이 된 경우 InspectionDate에 (예 제외한 점유> 빈> 점유> 점유> 빈> 빈하지만 비어 포함한> 빈> 빈 또는 빈> 점유 또는 빈)TSQL : X

이 I는 예를 들어 사용하고 단순화 된 표이다 :

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 
,210

내 결과는 다음과 같아야합니다

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 

이 충분히 명확하지 않은 경우 알려 주시기 바랍니다. having 조건이 참이면

+1

가능한 복제본 [TSQL : 주어진 파티션의 최상위 레코드 (조건부)] (http://stackoverflow.com/questions/38112133/tsql-the-top-records-of-a-given-partition-conditional) –

+0

@AlexKudryashev는 닫히기는하지만 완전히 동일하지는 않습니다. ID의 모든 인스턴스에 대해 두 개의 마지막 레코드가 비어 있으면 보게됩니다.이 ID는 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) 
); 

다음 vacants 모두가 occupieds 이후에 나타납니다 (또는 더미 날짜는 아무도 존재하지 않는 경우.)

여기 분석을 사용하여 동일한 접근 방식 :

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; 

계획을 확인하고 어느 것이 더 잘 작동하는지 확인하십시오.