SQL 查询排除任何满足一定条件的项目(占null)

SQL Query to exclude any items that meet a certain requirement (accounting for null)

我看到了类似的问题,但没有一个能完全回答这个问题,所以我会继续问。

我需要 select 一组设施,但一旦它们符合特定的一组标准,它们可能 不会 被包括在内。因此,如果提交月份与特定月份匹配,并且 FacWideAU、FacWideAR 或 AU = 1(非 0 或 null),则不能包含该设施。设施可能有多个结果。

Sample DB Example (only Hosp1 should qualify):

 HospID  |  HospName        |        FacWideAU   |  FacWideAR  |  AU
 ---------------------------------------------------------------
 1          Hosp1                    0
 2          Hosp2                    1             0            0
 2          Hosp2                    0                          0
 3          Hosp3                    1             1            0
 3          Hosp3                   
 3          Hosp3                    0

等等

有没有比下面的查询更简单的方法(重复所有 selection 逻辑,它有连接并且在现实中更复杂)?

非常感谢!

   Select distinct HospID, HospName
      from <Hospital Table>
      where Description='...whatever...'
      etc.

   and ID NOT in
   (
      Select distinct HospID 
         from <Hospital Table>
         where Description='...whatever...'
         etc.

         and (case when (TO_CHAR(SubmissionMonth, 'MON-YYYY') = 'Mar-2017' AND
         (FacWideAU = 1 or FacWideAR = 1 or AU = 1)) then 1 else 0 end) = 1
   )

只需为每一列添加一个空检查:

where FacWideAU IS NULL 
   or FacWideAU = 1 
   or FacWideAR IS NULL
   or FacWideAR = 1 
   or AU IS NULLor AU = 1

您可以删除 not in 部分并更改原始 where 部分:

where Description='...whatever...'
   and ((TO_CHAR(SubmissionMonth, 'MON-YYYY') != 'Mar-2017')
   or (FacWideAU IS NULL 
   and FacWideAU = 0 
   and FacWideAR IS NULL
   and FacWideAR = 0
   and AU IS NULL
   and AU = 0))

我找到了另一个解决方案:您可以在 table 上使用左连接。

Select distinct h1.HospID, h1.HospName
      from <Hospital Table> h1
      left join <Hospital Table> h2 on h1.HospId = h2.HospId
            and (((TO_CHAR(h2.SubmissionMonth, 'MON-YYYY') = 'Mar-2017')
            and (isnull(h2.FacWideAU, 0) = 1 or isnull(h2.FacWideAR, 0) = 1 or isnull(h2.AU, 0) = 1))

      where Description='...whatever...'
      and h2.id is null
      etc.