仅在符合条件时过滤数据

时间:2017-01-03 16:09:21

标签: sql sql-server sql-server-2008

我正在尝试配置此查询,但我无法想到这样做的方法。我的查询如下:

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'那么它们仍应出现在此列表中,但如果其出席状态设置为“是”&#39>。否则我不希望它们出现。

我在哪里可以添加此过滤器?

2 个答案:

答案 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()表达式计算条件的匹配数

答案 1 :(得分: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 ...