2017-01-03 144 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

加t 「內部查詢」中的軟管狀態 –

回答

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()表達計數匹配的條件

+0

謝謝戈登,像往常一樣樂於助人。完全按照我需要的那樣工作。 – Sp00kyy

0

,如果你想我只想補充另一個條件and exists數超出現有條件的附加條件如下:

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 ... 
相關問題