2017-01-03 14 views
1

나는이 쿼리를 구성하려고하는데 어떻게 할 수 있을지 생각하지 않습니다. 내 쿼리는 다음과 같습니다.기준이 맞을 때만 데이터 필터링

select per.Forenames, per.Surname, p.Identifier2 
from patient p 
join Person per on per.PersonID = p.PersonID 
where not exists (select 1 
       from Episode e 
       where e.PatientID = p.PatientID and 
        e.EpisodeTypeID in ('FCB9EAA0-C814-413E-A5FC-48547EF973B7', 
             'E422A8FA-839B-44AD-9A60-6973FEF39361', 
             '08929D40-863E-4D46-94BD-B4DF9352A855', 
             'C8BE80C4-AA0A-41ED-A44C-BCBE2CC980C0', 
             '8C3848C7-8621-43CF-A58D-D4A6ED4DC166', 
             'C244B01A-E9DD-4BF4-B336-1479A5A7C88D', 
             '632FAC1E-6B04-4A69-8BF2-0C2E2B0AD8AB' 
             ) and 

        e.EpisodeDate between '2016-04-01' and '2016-12-15' 

      ) 
and p.PatientStatus = 'Current' 
group by p.Identifier2, per.Forenames, per.Surname 

그래서이 쿼리는 지정된 에피소드 유형에 참석하지 않은 경우에만 특정 사람을 찾는 것입니다. 이제 내가하고 싶은 일은 이것을 더욱 더 필터링하는 것입니다. 나는 그들이 이있는 경우 ID '9254B31D-A304-498C-ADE4-F4003997C8FA'의 에피소드 유형에 참석 했으므로이 목록에 계속 나타나야하지만 에만 해당 상태가 설정된 경우 ~ '예'. 그렇지 않으면 나는 그들이 나타나길 원치 않는다.

어디에서이 필터를 추가 할 수 있습니까?

+0

내부 쿼리의 호스 상태 –

답변

1

로직의이 유형은 group byhaving 사용하여이 작업을 수행하는 것이 더 쉽습니다 :

select per.Forenames, per.Surname, p.Identifier2 
from patient p join 
    Person per 
    on per.PersonID = p.PersonID join 
    Episode e 
    on e.PatientID = p.PatientID 
group by per.Forenames, per.Surname, p.Identifier2 
having sum(case when e.EpisodeTypeID in ('FCB9EAA0-C814-413E-A5FC-48547EF973B7', 
             'E422A8FA-839B-44AD-9A60-6973FEF39361', 
             '08929D40-863E-4D46-94BD-B4DF9352A855', 
             'C8BE80C4-AA0A-41ED-A44C-BCBE2CC980C0', 
             '8C3848C7-8621-43CF-A58D-D4A6ED4DC166', 
             'C244B01A-E9DD-4BF4-B336-1479A5A7C88D', 
             '632FAC1E-6B04-4A69-8BF2-0C2E2B0AD8AB' 
             ) and 
        e.EpisodeDate between '2016-04-01' and '2016-12-15' 
       then 1 else 0 
      end) = 0 and 
      sum(case when e.EpisodeTypeId = '9254B31D-A304-498C-ADE4-F4003997C8FA' and 
         e.AttendedStatus <> 'Yes' -- assumes AttendedStatus is not NULL 
        then 1 else 0 
       end) = 0; 

sum() 표현이 원한다면 난 그냥 and exists 또 다른 조건을 추가 할 수

+0

Gordon에게 감사드립니다. 항상 도움이됩니다. 내가 필요한만큼 정확하게 일했다. – Sp00kyy

0

조건에 일치의 수를 계산을 다음과 같은 기존 조건을 능가하는 추가 조건 :

select per.Forenames, per.Surname, p.Identifier2 
from patient p 
... 
and p.PatientStatus = 'Current' 
and exists (
    select 1 
    from Episode e1 
    where e1.PatientID = p.PatientID 
    and e1.EpisodeTypeID = '9254B31D-A304-498C-ADE4-F4003997C8FA' 
    and e1.AttendedStatus = 'Yes' 
    ) 
group by ...